Given a situation like: Company
has_many Users
To get the Companies that have 3 Users, this works efficiently:
Company.joins(:users).group("companies.id").having("COUNT(users.id)=3")
But what's the most efficient way to get the Companies that have 0 Users (none)? Because, obviously, the same approach would not work (as joins
by definition excludes Companies with 0 Users):
Company.joins(:users).group("companies.id").having("COUNT(users.id)=0")
Do a LEFT JOIN instead of INNER JOIN.
Company.joins('LEFT OUTER JOIN users ON companies.id = users.company_id')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With