Sylar Sylar - 3 months ago 5x
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.


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