如何过滤关联的对象?

时间:2019-05-15 06:07:08

标签: sql ruby-on-rails ruby rails-activerecord

我想要过滤包含/联接的关联模型。

practice.patients.joins('
  LEFT JOIN appointments on patients.id = appointments.patient_id 
  LEFT JOIN patient_treatments on patients.id = patient_treatments.patient_id
  LEFT JOIN invoices on patients.id = invoices.patient_id
  LEFT JOIN prescription_values on patients.id = prescription_values.patient_id'
  ).where('(appointments.created_at::date between :start_date and :end_date' ,{start_date: start_date, end_date: end_date })

我希望约会的患者在此日期范围内。

2 个答案:

答案 0 :(得分:1)

您只能使用eager_load加载过滤的关联对象。

看看这个例子

result = [YourModel].patients.eager_load(:appointments).where("appointments.created_at::date between :start_date and :end_date" ,{start_date: Date.yesterday, end_date: Date.today })

它将加载在昨天今天之间创建约会的患者。还将在指定的日期范围内加载关联的约会。

尝试做

result.first.appointments

希望对您有帮助!

答案 1 :(得分:0)

您可以尝试这样的事情。

practice.patients.includes(:appointments).where(appointments: { created_at: start_date..end_date }).group("patients.id")