Sylar Sylar - 1 year ago 65
Ruby Question

How to tell a model has an empty relation

There maybe an answer for this but I might not be searching with the correct words. How to tell my model has an association object? Makes sense?

#Foo Model:
has_one :bar

#User Model:
has_many :foos #=> {object}

Basically what I want is, give me all of
that has no
. Is this possible?

Instead of adding a table onto
has_bar: <boolean>
, then:

User.first.foos.where(has_bar: false)


This maybe a duplicate post based on Albin's answer. But it still works for Rails 5.

Answer Source

If you read the answers in this question you will find multiple ways of doing it: Want to find records with no associated records in Rails 3

The way I would do it is:

User.first.foos.includes(:bar).where(bars: { foo_id: nil } )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download