如何判断一个模型有一个空关系

How to tell a model has an empty relation

这个问题可能有答案,但我可能没有使用正确的词进行搜索。如何告诉我的模型有关联对象?有道理吗?

#Foo Model:
 has_one :bar

#User Model:
 has_many :foos

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

基本上我想要的是,把没有barfoos都给我。这可能吗?

而不是在 foo 上添加 table:has_bar: <boolean>,然后:

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

编辑:

这可能是 duplicate post 基于 Albin 的回答。但它仍然适用于 Rails 5.

如果你阅读了这个问题的答案,你会发现有多种方法可以做到:Want to find records with no associated records in Rails 3

我的做法是:

User.first.foos.includes(:bar).where(bars: { foo_id: nil } )
User.first.foos.select { |foo| foo.include(:bar) && foo.bar.id.nil? }