zedge
zedge

Reputation: 81

How to make a query to get a model with an empty attribute

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

Answers (1)

Udo
Udo

Reputation: 51

You can use includes and where to filter only Foo without bars:

Foo.includes(:bars).where(bars: {foo_id: nil})

Upvotes: 1

Related Questions