Skip to content

Instantly share code, notes, and snippets.

@owen2345
Created May 30, 2018 14:40
Show Gist options
  • Save owen2345/a4dc31460d21eaec0b7855a07b4f3fad to your computer and use it in GitHub Desktop.
Save owen2345/a4dc31460d21eaec0b7855a07b4f3fad to your computer and use it in GitHub Desktop.
class CommentsController < ApplicationController
def users_comments
# SOLUTION 1: a bit complicated to add pagination and its sql performance is bad when there is a lot of comments,
# because the sql query is returning all matched comments
@user_comments = Post.all.includes(:comments).eager_load(comments: :author)
.where(author: {username: params[:username]}).map(&:comments)
.flatten
# SOLUTION 2: easy to add pagination and its sql performance is much better
@user_comments = Comment.joins(:post, :author).where(author: {username: params[:username]})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment