简体   繁体   中英

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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