2015-09-17 64 views
5

如果我有一个Post s的集合,是否有无法使用方法链或范围获取所有这些帖子的所有Comment通过has_many关系获取收集的所有孩子

例如:

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

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

回答

2

最好的办法:

​​

或者如果你有一个posts变量是一个ActiveRecord关系:

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

当然,也有一些方法。您可以使用mapflatten,对于少量记录可以使用。请确保您使用includes批量加载评论。

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

或者您可以使用连接。这会在数据库上增加更多的工作,这可能会更快,但取决于您的模式和数据集。您通常需要使用uniq来防止重复。

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

此外,请确保您完全限定连接表上任何子句中的任何显式片段,例如,使用where('posts.created_at < ?', ...)而不是where('created_at < ?', ...)

编辑:

第一另一变型,如果你想返回的关系(可进一步作用域的路线):

Comment.where(id: Post.where(published: true).pluck(:id)) 
+0

也许'Comment.where(post_id:'? – hlcs