如何过滤关联对象?

How can I filter on associated objects?

我想要对 included/joined 个关联模型进行筛选。

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 })

我想要在此日期范围内预约的患者。

你可以尝试这样的事情。

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

您只能使用 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

希望对您有所帮助!