2012-05-24 114 views

回答

2

你可以使用一个不存在这样的:

Post.where(" not exists (select 'x' from comments where comments.post_id = posts.id)") 
+0

我会使用一个计数器缓存,避免子查询。如果你有很多评论,这可能会不必要的缓慢。 – DanS

3

为了获得更好的性能,使用counter_cache柱:

belongs_to :post, :counter_cache => true

api.rubyonrails.orgRailscasts

然后,你可以这样做:

Post.where("comments_count = ?", 0)