如何进行查询以获取具有空属性的模型
How to make a query to get a model with an empty attribute
我有一个模型 Foo
has_many
Bar
。
我想要一个 return 全部 Foos
没有 Bar
或为空的查询。
然后我想应用计数或长度来查看有多少 Foos 没有 Bars。
我试过了:
Foo.where('bars.count = 0').count
Foo.where('bars = []').count
Foo.where('bars.count = ?', 0).count
全部 return 一个 Postgresql 错误。
您可以使用 includes 和 where 只过滤没有条形的 Foo:
Foo.includes(:bars).where(bars: {foo_id: nil})
我有一个模型 Foo
has_many
Bar
。
我想要一个 return 全部 Foos
没有 Bar
或为空的查询。
然后我想应用计数或长度来查看有多少 Foos 没有 Bars。
我试过了:
Foo.where('bars.count = 0').count
Foo.where('bars = []').count
Foo.where('bars.count = ?', 0).count
全部 return 一个 Postgresql 错误。
您可以使用 includes 和 where 只过滤没有条形的 Foo:
Foo.includes(:bars).where(bars: {foo_id: nil})