【问题标题】:How to tell a model has an empty relation如何判断模型的关系为空
【发布时间】:2016-07-07 06:57:16
【问题描述】:

也许有一个答案,但我可能没有用正确的词搜索。如何告诉我的模型有关联对象?有意义吗?

#Foo Model:
 has_one :bar

#User Model:
 has_many :foos

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

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

而不是将表格添加到foohas_bar: <boolean>,然后:

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

编辑:

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

【问题讨论】:

    标签: ruby-on-rails ruby postgresql ruby-on-rails-5


    【解决方案1】:

    如果您阅读此问题的答案,您会发现有多种方法:Want to find records with no associated records in Rails 3

    我的做法是:

    User.first.foos.includes(:bar).where(bars: { foo_id: nil } )
    

    【讨论】:

    • 谢谢,但我有has_oneUser.first.foos.includes(:bar).where(bars: {foo_id: nil})。我已经为链接投票,但你有一个小小的错字。更新,我会回答。也许是重复的帖子?
    • 我似乎无法编辑你的答案。请在 cmets 中更改我的建议。你的回答还是不行。
    【解决方案2】:
    User.first.foos.select { |foo| foo.include(:bar) && foo.bar.id.nil? }
    

    【讨论】:

    • Foo 上没有关联 ID。阿尔宾指出我正确的帖子/答案。看看吧。
    • 感谢您指出这一点,我还没有醒来(:我用另一种可能的替代方法更新了它,谢谢!@Sylar
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2018-07-21
    • 2019-03-20
    • 2022-01-23
    相关资源
    最近更新 更多