Reputation: 81
I have a model Foo
that has_many
Bar
.
I want a query that returns all Foos
that have no Bar
, or empty.
Then I want to apply count or length to see how many Foos doesn't have Bars.
I tried:
Foo.where('bars.count = 0').count
Foo.where('bars = []').count
Foo.where('bars.count = ?', 0).count
All of them return a Postgresql error.
Upvotes: 0
Views: 145
Reputation: 51
You can use includes and where to filter only Foo without bars:
Foo.includes(:bars).where(bars: {foo_id: nil})
Upvotes: 1