在has_many关联中为“no children”创建named_scope

我想为没有post的博客提供一个named_scope。

以下不起作用。

class Post < ActiveRecord::Base belongs_to :blog end class Blog  "blogs.id NOT IN (SELECT blog_id FROM posts)" end 

你确定它不起作用吗? 这个对我有用。

不确定为什么你的代码不起作用。 是否错误返回您的期望? 你可以发布它生成的sql吗?

但是你可以尝试:

 named_scope :has_no_posts, :include => [:posts], :conditions => "posts.id IS NULL"