【问题标题】:How to make a query to get a model with an empty attribute如何进行查询以获取具有空属性的模型
【发布时间】:2021-02-16 18:25:50
【问题描述】:

我有一个模型 Foo 那个 has_many Bar。 我想要一个返回所有没有Bar 或为空的Foos 的查询。 然后我想应用 count 或 length 来查看有多少 Foos 没有 Bars。

我试过了:

Foo.where('bars.count = 0').count
Foo.where('bars = []').count
Foo.where('bars.count = ?', 0).count

它们都返回一个 Postgresql 错误。

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord


    【解决方案1】:

    您可以使用包含和位置来仅过滤没有条的 Foo:

    Foo.includes(:bars).where(bars: {foo_id: nil})
    

    【讨论】:

      猜你喜欢
      • 2022-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 2016-02-04
      • 2014-05-04
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多