Sylar Sylar - 5 months ago 10
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

User.first.foos.bar #=> {object}


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

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

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


Edit:

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

Answer

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 } )