Search code examples
ruby-on-railsruby-on-rails-3has-many-throughactivemodelruby-on-rails-4

Retrieve subset of many-to-many relationship in Rails/ActiveModel


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?


Solution

  • You should be able to do

    has_many :patients, :through => :appointments do
      def active
        where("appointments.finished_at is NULL")
      end
    end
    

    then:

    doctor.patients.active