Rails Scope for association of 0 size.

Posted by MissingHandle on Stack Overflow See other posts from Stack Overflow or by MissingHandle
Published on 2011-06-21T19:57:47Z Indexed on 2011/06/22 0:22 UTC
Read the original article Hit count: 120

Filed under:
|

I'm having trouble figuring out the scope method for all the Foos that have no Bars. That is:

class Foo < ActiveRecord::Base

  has_may :bars

end

class Bar < ActiveRecord::Base

  belongs_to :foo

end

I'd like to write a scope method that returns me all the foos that have no bars. Something like:

class Foo < ActiveRecord::Base

  has_may :bars

  scope :has_no_bars, includes(:bars).where("COUNT(foo.bars) = 0")

end

But I don't understand the appropriate syntax. Any help? Happy to use a MetaWhere solution if easier.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord