Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Has_many through query depending on the through table attribute

Having some problems with a has_many through query.

Using the example here: http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end

The Appointment table has a column named appointment_date

How would I get all the Patients from a Specific Physician that have an appointment on a given date?

like image 917
Ghar Avatar asked Mar 26 '13 15:03

Ghar


1 Answers

Patient.includes(:physicians, :appointments).where('physicians.id = ? AND appointments.appointment_date = ?', <id or ids array>, Date.today)

Where Date.today could be changed with anything and the pysician is specified by an id or an array of ids.

You could also do:

physician = Physician.find(id)
patients = physician.patients.includes(:appointments).where('appointments.appointment_date  = ?', some_date)

Edit:

In Rails 4 and forward, you need to add references(:appointments) to the query in order to use appointments in the where clause.

like image 181
spullen Avatar answered Oct 21 '22 18:10

spullen