首页 > 解决方案 > 如何进行查询以获取具有空属性的模型

问题描述

我有一个Foo模型has_many Bar。我想要一个返回所有Foos没有Bar或空的查询。然后我想应用计数或长度来查看有多少 Foos 没有 Bars。

我试过了:

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

它们都返回一个 Postgresql 错误。

标签: ruby-on-railsactiverecordrails-activerecord

解决方案


您可以使用 include 和 where 仅过滤 Foo 而没有条:

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

推荐阅读