ruby-on-rails - Rails 范围根据其子项的属性(或没有子项)
问题描述
我有 2 个模型:Sophead
和SopheadIssue
.
SopheadIssue belongs to Sophead
,
Sophead has many SopheadIssues
(可选的)。
我想在 Sophead 模型上为符合以下 2 个条件之一的 Sophead 创建一个范围:
- Sophead 根本没有 SopheadIssues
- Sophead 没有 SopheadIssue 属性为 (active=true) 的 SopheadIssues。
目前我尝试了以下方法:
scope :no_issue, -> { joins(:sophead_issues).where.not("active = ?", true) }
但这不起作用,因为它缺少没有任何 SopheadIssues 的 Sopheads。
非常感谢任何帮助。
非常感谢!
解决方案
问题是,joins
它INNER JOIN
过滤掉了sophead
without sophead_issues
。您需要在此处使用left_joins:
scope :no_issue, -> { left_joins(:sophead_issues).where("sophead_issues.active != ? OR sophead_issues.sophead_id IS NULL", true) }
推荐阅读
- javascript - 将错误从 POST 路由传递到 ejs 模板
- numpy - 如何使用 Keras 将输入和输出数据拟合到连体网络中?
- angular - 2 以角度输入指令
- html - 如何解决我的网址被更改的问题
- mysql - 带有 where 子句的内部连接不需要的结果
- javascript - 在字符串/消息中查找单词短语(不仅仅是单个单词,而是一个句子)并从数组返回响应
- javascript - 如何将对象添加到数组并在用户单击时将其删除?
- nginx - 如何在剖析查询字符串时进行 nginx 重定向?
- jquery - 未捕获的类型错误:无法读取未定义的属性“innerHTML”,如果跨度文本为空
- android - 创建一个可折叠的侧边栏 - 导航抽屉的替代品?