7

If I have a collection of Posts, is there anyway to get all Comments for all of those posts using method chaining or scopes?

For example:

posts = Post.where(published: true)
comments = posts.comments

# vs 
comments = []
posts.each do |post|
  comments.push(post.comments)
end

2 Answers 2

10

Sure, there are a few ways. You can can use map and flatten, which is fine for a small number of records. Make sure you load the comments in bulk by using includes.

Post.where(published: true).includes(:comments).map(&:comments).flatten

Or you can use a join. This puts more work on the database, which is likely faster, but depends on your schema and dataset. You will typically want to use uniq to prevent duplicates.

posts = Post.where(published: true)
Comment.joins(:post).merge(posts).uniq

Also, make sure that you fully qualify any explicit fragments in any clauses on joined tables, e.g. use where('posts.created_at < ?', ...) instead of where('created_at < ?', ...).

Edit:

Another variant on the first, in case you want to return a relation (which can be further scoped down the line):

Comment.where(id: Post.where(published: true).pluck(:id))
1
  • 1
    Maybe Comment.where(post_id:?
    – Artem P
    Commented Jun 25, 2017 at 10:28
3

Best way:

Comment.joins(:post).where(post: {published: true})

or if you have a posts variable that is a ActiveRecord Relation:

Comment.joins(:post).where(post: posts)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.