2011-07-21 49 views
2

我试图抓住帖子,并只根据条件属于该帖子的评论:如何只:包括基于条件语句

即。

# Grab all posts but only include comments that have been approved. 
Post.all(:include => :comments, :conditions => ['comments.approved = ?', true]) 

更新2011年7月20日10:11 EST

为了澄清,我试图抓住所有的职位,只有特定用户的那个帖子的评论。

def grab_posts_and_only_comments_from(user) 
    {:include => [:comments], :conditions => ['comments.user_id = ?', user.id]} 
end 

修订二○一一年七月二十零日11:34 EST

答案在检查答案的评论。

+0

它不是澄清,而是一个新的问题实际上:) – fl00r

+0

抱歉。你知道我能做到吗?我愿意接受任何建议。 – jnoh

回答

3
Post.includes(:comments).where("comments.approved = ?", true) 

有关此功能的文档在EdgeGuides中有很大改进。查看第12.2节here

+0

嗯,这只会抓取帖子,如果该帖子有批准的评论。如果我希望它也包括没有批准评论的帖子,那么怎么办? – jnoh

+1

真的吗?你看过生成的SQL吗?根据文档,这种方法应该生成一个LEFT OUTER JOIN,它会给你所有的帖子,不管他们有没有评论。相比之下,使用.join(:comments)会产生一个INNER JOIN,它只包含带批准评论的帖子。 – cailinanne

+0

@jnoh,cailinanne是完全正确的 – fl00r

1

只需添加新的关联approved_comments

class Post < AR::Base 
    has_many :comments 
    has_many :approved_comments, :class_name => "Comment", :conditions => { :approved => true } 
end 

Post.includes(:approved_comments) 
# or for Rails 2.x 
Post.all(:include => :approved_comments) 

编辑

Post.includes(:approved_comments).where(:approved_comments => {:user_id => user.id}) 
+0

对不起,我应该澄清,我试图创建一个接收变量的作用域。我上面做了编辑。 – jnoh

+0

@jnoh,我已经更新了我的答案 – fl00r