简体   繁体   中英

Creating a named_scope for “no children” in a has_many association

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

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM