views:

36

answers:

2

I would like to have a named_scope for blogs with zero posts.

The following does not work.

class Post < ActiveRecord::Base
  belongs_to :blog
end

class Blog < ActiveRecord::Base
  has_many :posts

  named_scope :has_no_posts, :conditions => "blogs.id NOT IN (SELECT blog_id FROM posts)"
end
A: 

Are you sure it does not work? It works for me.

Sławosz
A: 

Not sure why your code does not work. Does it error or not return what you expect? Can you post the sql it generates?

However you could try:

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