简体   繁体   English

rails-在通过模型填充之前检查

[英]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. p =患者的目标。

so, p.appointments.append (physican_obj) is the proper way. 因此,p.appointments.append(physican_obj)是正确的方法。 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. 这将确保不允许同时复制两个ID的记录。

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

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