【问题标题】:Rails ActiveRecord model scope with joins on has_many associationsRails ActiveRecord 模型范围与 has_many 关联上的连接
【发布时间】: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 &lt; :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


【解决方案1】:

Rails 5 更新

正如mad_raz 提到的,在Rails 5.0+ 中,您可以使用left_outer_joins:

scope :awaiting_quote, -> { joins(:surveys).
  left_outer_joins(:quotes).
  where('survey_date < :current_time', { current_time: Time.current }).
  where('quotes.id IS NULL')
}

但是,您仍然必须提供where('quotes.id IS NULL') 支票才能仅返回那些尚未收到报价的记录。请参阅 https://stackoverflow.com/a/16598900/1951290 以获得外部连接的出色视觉表示。

将它们分成两个单独的范围可能仍然是最有意义的。


Rails 4

您可以使用joins 创建左外连接,您只需要更明确一点。

scope :awaiting_quote, -> { joins(:surveys).
  joins('LEFT OUTER JOIN quotes ON quotes.job_id = jobs.id').
  where('survey_date < :current_time', { current_time: Time.current }).
  where('quotes.id IS NULL')
}

您不需要surveys.id IS NOT NULL,因为成功的内部连接不会包含 nil id。

将它们分成两个单独的范围可能更有意义,:has_survey 和 :without_quote,然后可以将它们组合成一个方法。

def self.awaiting_quote
  Job.has_survey.without_quote
end

【讨论】:

    【解决方案2】:

    Rails 5 引入了可以使用的left_outer_joins 方法

    scope :awaiting_quote, -> { joins(:surveys).left_outer_joins(:quotes).where('yada yada') }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多