0

例如,我的医生与患者有很多约会。我想检索当前在约会中处于活动状态的所有患者:

class Doctor < ActiveRecord::Base
  attr_accessible :name
  has_many :appointments
  has_many :patients, through: :appointments
end

和约会模型:

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

现在我可以做一些事情doctor.appointments.active来获取当前的活跃约会。但我想轻松地让患者接受这些预约。反正有做类似的事情doctor.appointments.active.patients吗?或者doctor.patients.active会更有意义。

我可以将active范围添加到has_many :patientsDoctor 类的行中吗?

4

1 回答 1

1

你应该能够做到

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

然后:

doctor.patients.active
于 2013-05-20T17:46:11.263 回答