1

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.

Community
  • 1
  • 1
Sylar
  • 11,422
  • 25
  • 93
  • 166

2 Answers2

1

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 } )
Community
  • 1
  • 1
Albin
  • 2,912
  • 1
  • 21
  • 31
  • Thanks but I have the `has_one`: `User.first.foos.includes(:bar).where(bars: {foo_id: nil})`. I have upvoted for the link but you have a tiny typo. Update and I'll answer. Maybe a duplicate post? – Sylar Jul 07 '16 at 07:28
  • I cant seem to edit you answer. Please to change to my suggestion in comments. Your answer still does not work. – Sylar Jul 07 '16 at 12:38
1
User.first.foos.select { |foo| foo.include(:bar) && foo.bar.id.nil? }
fabriciofreitag
  • 2,843
  • 22
  • 26
  • There isnt an association id on `Foo`. Albin has pointed me to the correct post/answer. Have a look. – Sylar Jul 07 '16 at 08:13
  • Thanks for pointing that out, I didn't wake up yet (: I updated it with another possible alternative, thanks! @Sylar – fabriciofreitag Jul 07 '16 at 08:37