【问题标题】:Rails 3 scope with multiple models具有多种模型的 Rails 3 范围
【发布时间】:2012-08-02 00:37:03
【问题描述】:
这是我的模型:
患者:
has_many :patient_records
病历:
belongs_to :patient
has_many :progress_reports
进度报告:
has_one :patient_record
我正在尝试生成的查询是在包含或加入患者记录表时获取所有progress_reports 大于或等于7 天的患者(使用progress_reports 中的date_of_report 列)...我一直在工作这么久了,我都碰上了砖墙。
【问题讨论】:
标签:
ruby
ruby-on-rails-3
activerecord
model
scope
【解决方案1】:
我会尝试:
scope :recent_patients, lambda
{ |since_when| join(:progress_reports)
.where("progress_reports.created_at >= ?", since_when)}
在您的 Patient 模型中
【解决方案2】:
reports = ProgressReport.where(:created_at > 7.days.ago).all
如果您想获取属于每条记录的每个患者,请执行以下操作:
reports.each do |r|
puts r.patient.name
end