创建has_many:有条件地通过Association

时间:2016-06-20 16:26:59

标签: ruby-on-rails ruby-on-rails-4

我有以下课程:

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, through: :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, through: :appointments
end

我只希望医生能够创建约会,但不能创建患者。请告诉我如何在模型级别获得此限制。

谢谢!

1 个答案:

答案 0 :(得分:2)

您无需使用关联来检索患者约会。只需为它们创建一个getter方法:

class Patient < ActiveRecord::Base
  def appointments
    Appointment.where(patient_id: self.id)
  end
end