首页 > 解决方案 > Rails 范围根据其子项的属性(或没有子项)

问题描述

我有 2 个模型:SopheadSopheadIssue.

SopheadIssue belongs to Sophead,

Sophead has many SopheadIssues(可选的)。

我想在 Sophead 模型上为符合以下 2 个条件之一的 Sophead 创建一个范围:

  1. Sophead 根本没有 SopheadIssues
  2. Sophead 没有 SopheadIssue 属性为 (active=true) 的 SopheadIssues。

目前我尝试了以下方法:

scope :no_issue, -> { joins(:sophead_issues).where.not("active = ?", true) }

但这不起作用,因为它缺少没有任何 SopheadIssues 的 Sopheads。

非常感谢任何帮助。
非常感谢!

标签: ruby-on-railsrubyactiverecord

解决方案


问题是,joinsINNER JOIN过滤掉了sopheadwithout sophead_issues。您需要在此处使用left_joins

scope :no_issue, -> { left_joins(:sophead_issues).where("sophead_issues.active != ? OR sophead_issues.sophead_id IS NULL", true) }

推荐阅读