我有 2 个模型:Sophead
和 SopheadIssue
。
SopheadIssue属于Sophead
,
Sophead 有很多 SopheadIssues
(可选)。
我想在 Sophead 模型上为满足以下 2 个条件之一的 Sopheads 创建一个范围:
- Sophead 完全没有 SopheadIssues
- Sophead 没有 SopheadIssues 的 SopheadIssue 属性为 (active=true)。
目前我尝试了以下方法:
scope :no_issue, -> { joins(:sophead_issues).where.not("active = ?", true) }
但这不起作用,因为它缺少没有任何 SopheadIssues 的 Sopheads。
非常感谢任何帮助。
非常感谢!
最佳答案
问题是 joins
是 INNER JOIN
并且它过滤掉 sophead
而没有 sophead_issues
。您需要使用 left_joins这里:
scope :no_issue, -> { left_joins(:sophead_issues).where("sophead_issues.active != ? OR sophead_issues.sophead_id IS NULL", true) }
关于ruby-on-rails - 根据其子项(或没有子项)的属性的 Rails 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51860007/