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.
You need either a sub-select or an outer join + group + unique to solve your problem. AFAIK that is not possible with Rails’ AR.
An approximation would be to use AR’s counter-cache feature and make your query as simple as
This isn’t 100% correct relation-wise but saves you a lot of work and also scales much better.