开发者

Creating a named_scope for "no children" in a has_many association

开发者 https://www.devze.com 2023-01-16 00:48 出处:网络
I would 开发者_如何学JAVAlike to have a named_scope for blogs with zero posts. The following does not work.

I would 开发者_如何学JAVAlike 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"
0

精彩评论

暂无评论...
验证码 换一张
取 消