Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix N+1 problem #69

Merged
merged 1 commit into from Jun 2, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/controllers/microposts_controller.rb
Expand Up @@ -22,7 +22,7 @@ def destroy

def search
@micropost = current_user.microposts.build
@feed_items = Micropost.content_like(params[:content]).page params[:page]
@feed_items = Micropost.includes(:user).content_like(params[:content]).page params[:page]
end

def likes
Expand Down
8 changes: 3 additions & 5 deletions app/models/user.rb
Expand Up @@ -71,10 +71,8 @@ def password_reset_expired?
end

def feed
following_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
Micropost.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
following_ids = "SELECT followed_id FROM relationships WHERE follower_id = :user_id"
Micropost.includes(:user).where("user_id IN (#{following_ids}) OR user_id = :user_id", user_id: id)
end

def follow(other_user)
Expand All @@ -96,7 +94,7 @@ def send_followed_notification_email(user)
def liked_microposts
ids = []
likes.each { |like| ids << like.micropost_id }
Micropost.where(id: ids)
Micropost.includes(:user).where(id: ids)
end

private
Expand Down
2 changes: 1 addition & 1 deletion app/views/microposts/_micropost.html.haml
Expand Up @@ -10,4 +10,4 @@
= micropost.content
= image_tag micropost.picture.url if micropost.picture?
%span.like
= render 'likes/like_form', micropost: @micropost = micropost, users: @users = micropost.liked_users
= render 'likes/like_form', micropost: @micropost = micropost, users: @users = Micropost.includes(:likes).find(micropost.id).liked_users