0

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?

at.
  • 50,922
  • 104
  • 292
  • 461

1 Answers1

1

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
Joshua Scott
  • 645
  • 5
  • 9
  • it strangely doesn't work. The SQL it outputs makes sense, but I get back an empty set even though the appoints.finished_at is in fact `nil` – at. May 21 '13 at 18:14
  • the `finished_at` field is `nil` in Ruby. However, when I go to sqlite3, the field is empty.. I don't know what it is. If I do `sqlite> select * from appointments where finished_at=null;` I get nothing back. Even if I do `where finished_at=''` I get nothing back as well. – at. May 21 '13 at 18:25
  • If I type the following in `rails console` I do get back the appointment, weird how `nil` works in Rails but not in sqlite3: `Appointment.where(finished_at: nil)` – at. May 21 '13 at 18:27
  • Ok, I figured it out, apparently in SQL you can't check for NULL with `=`. You have to do the following: `appointments.finished_at is ?` – at. May 21 '13 at 18:29
  • I updated the where statement to be pure SQL, since that is all we need. Sorry about that. – Joshua Scott May 21 '13 at 21:23