1

I have a lot of posts with multiple comments, but I need to show posts with all the information and the latest comment for each post.

With a simple approach that I have an additional request for comments table for each post.

How can I get a list of posts with recent comments without the N+1 problem?

My case is very common - list of posts, with last comment.

maksfromspb
  • 177
  • 10

1 Answers1

1

You can use .includes to eager load objects you know you'll be using. I think my logic is correct and you'll end up with a unique list of posts where at least one of their comments meets your criteria.

def recently_updated_posts    
  comments = Comment.includes(:post).where("updated_at > ?", some_time)
  list_of_posts = posts.comments.map { |c| c.post }
  return list_of_posts.uniq!
end

You may be able to reduce the query load further by having a nested includes statement, as silly as it looks:

Comment.includes(posts: :comments).where("updated_at > ?", some_time)

More here: Rails - Nested includes on Active Records?

Community
  • 1
  • 1
Joe Essey
  • 3,457
  • 8
  • 40
  • 69
  • Thank for info about nesting includes - it's really useful, but in my case I need get posts with and without a comment, and comment must be last, ordered by Id. – maksfromspb Jan 27 '15 at 21:20