让我们说作者有很多帖子,帖子有很多评论。 你如何选择特定作者特定的几篇帖子的所有评论?
使用案例:我希望每篇关于作者帖子的最新评论都带有“rails”标签
@author = Author.find(params[:author_id])
@posts = @author.posts.where(:tag => 'rails')
现在
@comments = @posts.?????.where(:created_at.gte = 1.month.ago)
答案 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)