在Rails / ActiveModel中检索多对多关系的子集

时间:2013-05-20 16:42:04

标签: ruby-on-rails ruby-on-rails-3 has-many-through activemodel ruby-on-rails-4

作为一个例子,我有医生与患者约会。我想要检索所有目前在约会中活动的患者:

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范围添加到Doctor类的has_many :patients行吗?

1 个答案:

答案 0 :(得分:1)

你应该能够做到

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

然后:

doctor.patients.active