As an example, I have Doctors with many Appointments with Patients. I want to retrieve all Patients who are currently active in an Appointment:
class Doctor < ActiveRecord::Base
attr_accessible :name
has_many :appointments
has_many :patients, through: :appointments
end
And the Appointment model:
class Appointment < ActiveRecord::Base
attr_accessible :patient_id, :began_at, :finished_at, :doctor_id
belongs_to :patient
belongs_to :doctor
scope :active, where(finished_at: nil)
end
Now I can do something like doctor.appointments.active
to get the active current appointments. But I want to get the patients easily of those appointments. Is there anyway to do something like doctor.appointments.active.patients
? Or doctor.patients.active
would make more sense.
Can I add the active
scope to the has_many :patients
line in the Doctor class?