【发布时间】:2015-05-19 15:50:50
【问题描述】:
我目前正在我的 Rails 模型中设置一个范围以供 ActiveAdmin 使用。我要构建的范围应该找到过去有 survey_date 的每个 Job,现在有 Job.survey,没有 Job.quotes。
这是我的Job 模型的缩略版:
has_many :quotes
has_many :surveys
scope :awaiting_quote, lambda { joins(:surveys, :quotes).where('survey_date < :current_time AND surveys.id IS NOT NULL AND quotes.id IS NULL', { current_time: Time.current }) }
我应该如何更改我的范围,以便正确找到相关的Job 记录?
【问题讨论】:
-
请注意
joins将创建一个 INNER JOIN 这意味着quotes.id IS NULL没有影响并且这些作业将永远不会出现尝试includes(:surveys,:quotes).where('survey_date < :current_time AND surveys.id IS NOT NULL AND quotes.id IS NULL', { current_time: Time.current })这将创建 2 个 LEFT OUTER JOIN 并且可能会更好地运行为你。这是一个很棒的article 关联加载以及这些方法的工作原理
标签: ruby-on-rails ruby activerecord model active-record-query