简体   繁体   English

有条件地通过关联创建has_many:

[英]Creating has_many :through Association conditionally

I have the following classes: 我有以下课程:

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

I want only a Physician to be able to create an Appointment, but not a Patient. 我只希望医师能够创建一个约会,而不能创建一个病人。 Please let me know how I can have this restriction at the Model level. 请让我知道如何在模型级别上具有此限制。

Thanks! 谢谢!

You don't need to use the association to retrieve patients appointmets. 您无需使用关联来检索患者约会对象。 Just create a getter method for them: 只需为他们创建一个getter方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM