0

假装我有一个模型, Post 其中 has_many :comments。如何只显示有评论的帖子?

我对 named_scope 有点满意,但我不知道如何将 Post.comments(或 self.comments)放入需要符号的 :conditions 散列中。

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

我在评论区写什么?

谢谢!

4

2 回答 2

2

您应该能够只加入您的评论表,确保选择不同的行

named_scope :with_comments, :joins => :comments, :select => 'DISTINCT posts.*'
于 2009-06-16T22:27:55.913 回答
1

最好在 Post 上放置一个 counter_cache。

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

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

Post.find(:all, :conditions => ["counter_cache > 0"])

于 2009-06-17T03:53:07.703 回答