ruby-on-rails - 如何进行查询以获取具有空属性的模型
问题描述
我有一个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 错误。
解决方案
您可以使用 include 和 where 仅过滤 Foo 而没有条:
Foo.includes(:bars).where(bars: {foo_id: nil})
推荐阅读
- java - 检查文本文件中的项目是否为 JSON 格式 Android Studio
- typescript - TypeScript 可区分联合在切换后无法缩小类型
- python - 使用 lmfit 创建更精细的复合模型
- mysql - 无法将 MySql 查询(ManyToMany 关系)转换为 HQL
- python - SKlearn 导入错误
- php - 字段不接受默认值 mysql
- asp.net-mvc - 将数据作为参数从 MVC 应用程序传递给逻辑应用程序
- arrays - Postgres 字符串数组比较
- python - Python Matplotlib如何在同一个图中绘制多个图
- html - 设置自定义滑块控件 (CSS) 的位置