选择特定帖子的所有评论mongoid 2 rails 3.1

时间:2012-12-23 07:00:43

标签: ruby-on-rails mongodb mongoid

让我们说作者有很多帖子,帖子有很多评论。 你如何选择特定作者特定的几篇帖子的所有评论?

使用案例:我希望每篇关于作者帖子的最新评论都带有“rails”标签

@author = Author.find(params[:author_id])
@posts = @author.posts.where(:tag => 'rails')

现在

@comments = @posts.?????.where(:created_at.gte = 1.month.ago)

1 个答案:

答案 0 :(得分:2)

无法通过@posts.?????

执行此操作

您应该抓住帖子ID并选择评论

post_ids = @author.posts.where(:tag => 'rails').map(&:id)
# In rails >= 3.2.1 you can use pluck(:id) instead of map(&:id)

@comments = Comment.where(:post_id => post_ids, :created_at.gte = 1.month.ago)

更新:

@posts = @author.posts.where(:tag => 'rails')
@comments = Comment.where(:post_id => @posts.map(&:id), :created_at.gte = 1.month.ago)