dav*_*n88 1 ruby activerecord ruby-on-rails
我有2个模型:Sophead和SopheadIssue。
SopheadIssue belongs to Sophead,
Sophead has many SopheadIssues (可选的)。
我想在Sophead模型上为与2个条件中的EITHER匹配的Sopheads创建范围:
目前,我尝试了以下方法:
scope :no_issue, -> { joins(:sophead_issues).where.not("active = ?", true) }
Run Code Online (Sandbox Code Playgroud)
但这不起作用,因为它缺少没有任何SopheadIssues的Sophead。
任何帮助,不胜感激。
非常感谢!
问题是,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) }
Run Code Online (Sandbox Code Playgroud)