假装我有一个模型,帖子has_many:评论。我怎样才能显示有评论的帖子?

我对named_scope感觉有点舒服,但我不知道如何将Post.comments(或self.comments)放在:期望符号的条件哈希中。

class Post < ActiveRecord::Base
     has_many :comments
     named_scope :with_comments, :conditions => [#self.comments.length > 0]
end

我在评论区写什么?

谢谢!

有帮助吗?

解决方案

最好是将post_cache放在Post上。

class Comment < AR:Base
  belongs_to :post, :counter_cache => true
end

然后你只需要做1个查询而不是2个。

Post.find(:all,:conditions =&gt; [&quot; counter_cache&gt; 0&quot;])

其他提示

您应该可以加入评论表,确保选择不同的行

named_scope :with_comments, :joins => :comments, :select => 'DISTINCT posts.*'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top