【发布时间】:2015-05-20 18:47:44
【问题描述】:
我正在我的 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
【问题讨论】:
-
您可以发布您的型号代码吗?鉴于良好的模型/关联设计,这似乎并不过分复杂。
-
当然,我已经用我的模型代码更新了问题。
-
你有没有想过使用类方法来代替?
-
where 子句使用单数模型名称,但表格是复数形式。当您将字符串传递给
where时,它被假定为 SQL 片段。 -
我仍然非常坚持这一点。我将如何编辑我的答案以使范围正常工作?
标签: ruby-on-rails activerecord scope rails-activerecord rails-models