2012-12-23 118 views
0

可以说一个作者有很多帖子,一个帖子有很多评论。 你怎么能选择特定作者特定几篇文章的所有评论?选择特定帖子的所有评论mongoid 2 rails 3.1

使用案例:我想最近的每一个作者的与标签“轨道”

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

现在

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

回答

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) 

UPD:

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

你能缩短到:Comment.where(:POST_ID => @ posts.map(&:ID)) –

相关问题