假设一个作者有很多帖子,而一个帖子有很多评论。您如何选择特定作者特定少数帖子的所有评论?
用例:我想要最近对带有标签“rails”的作者帖子的评论
@author = Author.find(params[:author_id])
@posts = @author.posts.where(:tag => 'rails')
现在
@comments = @posts.?????.where(:created_at.gte = 1.month.ago)
假设一个作者有很多帖子,而一个帖子有很多评论。您如何选择特定作者特定少数帖子的所有评论?
用例:我想要最近对带有标签“rails”的作者帖子的评论
@author = Author.find(params[:author_id])
@posts = @author.posts.where(:tag => 'rails')
现在
@comments = @posts.?????.where(:created_at.gte = 1.month.ago)
没有办法通过@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)