Reputation: 12092
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.
Upvotes: 1
Views: 91
Reputation: 3032
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 } )
Upvotes: 1
Reputation: 2883
User.first.foos.select { |foo| foo.include(:bar) && foo.bar.id.nil? }
Upvotes: 1