简体   繁体   中英

rails - check before populating through model

I have two models Physician and Patient, like below :

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

p = patient obj.

so, p.appointments.append (physican_obj) is the proper way. But, if I run the same command twice, it is adding the same thing twice. So, is it good to check if it already exists before appending ? Whats best way to do it ?

My requirement is, I get a list of objects to add it, so I need to loop over each object and append each object. If I need to check before appending, I need to check in every loop which is a costly process.

An approach is to use scope.

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

  validate_uniqueness_of :physician_id, scope: :patient_id
end

This will make sure a record which duplicates both two ids won't be allowed.

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