Rails ActiveRecord范围包含多个连接和has_one关联

时间:2015-05-20 18:47:44

标签: ruby-on-rails activerecord scope rails-activerecord rails-models

我正在我的Job模型中创建一些范围,ActiveAdmin将使用它来过滤管道各个阶段的作业。

我必须创建与其他表的连接以收集相关信息,这就是我遇到麻烦的地方。我在下面概述了我的逻辑和(非工作)尝试。

我如何重构这些以使它们正常工作?

# app/models/job.rb

# where job.survey exists AND job.appointment.appointment_date is in past AND job.quote doesn’t exist

scope :awaiting_quote, -> { joins(:survey).
  joins('LEFT OUTER JOIN quotes ON quote.job_id = jobs.id').
  joins('LEFT OUTER JOIN appointments ON appointment.job_id = jobs.id').
  where('appointment.appointment_date < :current_time', { current_time: Time.current }).
  where('survey.id IS NOT NULL').
  where('quote.id IS NULL')
}

# where job.quote exists AND job.quote_accepted is false

scope :awaiting_acceptance, -> { joins(:quote).
  joins('LEFT OUTER JOIN appointments ON quote.job_id = jobs.id').
  where('appointment.appointment_date < :current_time', { current_time: Time.current }).
  where('quote.id IS NOT NULL').
  where('quote_accepted = :quote_accepted', { quote_accepted: false })
}

has_one :quote
has_one :survey
has_one :appointment
has_one :surveyor, through: :appointment
accepts_nested_attributes_for :appointment, :allow_destroy => true
accepts_nested_attributes_for :survey, :allow_destroy => true

# app/models/quote.rb

belongs_to :job

# app/models/survey.rb

belongs_to :job

# app/models/appointment.rb

belongs_to :job
belongs_to :surveyor

# app/models/surveyor.rb

has_many :appointments
has_many :jobs, through: :appointments

1 个答案:

答案 0 :(得分:1)

由于表之间的列名没有冲突,所以诀窍是连接所有表,只需对组合数据执行where方法。

scope :awaiting_quote, -> {
  joins(:survey, :quote, :appointment).
  where('quote IS NULL').
  where('appointment_date < :current_time', current_time: Time.current)
}

scope :awaiting_acceptance, -> {
  joins(:quote, :appointment).
  where('appointment_date < :current_time', current_time: Time.current).
  where('quote IS NOT NULL').
  where('quote_accepted = :quote_accepted', quote_accepted: false)
}
相关问题