Muhammad Ali Hafeez
Muhammad Ali Hafeez

Reputation: 11

How can I filter on associated objects?

I want a filter on included/joined associated models.

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

I want patients with appointments in this date range.

Upvotes: 0

Views: 68

Answers (2)

M. Habib
M. Habib

Reputation: 653

You can load filtered associated objects only using eager_load.

Take a look at this example

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

It will load patients whose appointment is created between yesterday and today . Also it will load associated appointments in the specified date range.

Try doing

result.first.appointments

I hope it helps!

Upvotes: 1

Kamal Pandey
Kamal Pandey

Reputation: 1598

You could try something like this.

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

Upvotes: 0

Related Questions