[英]rails - check before populating through model
我有医师和患者两个模型,如下所示:
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 =患者的目标。
因此,p.appointments.append(physican_obj)是正确的方法。 但是,如果我两次运行相同的命令,它将两次添加相同的内容。 因此,在追加之前检查它是否已经存在,这是否很好? 最好的方法是什么?
我的要求是,获得要添加的对象列表,因此需要遍历每个对象并追加每个对象。 如果需要在添加之前进行检查,则需要在每个循环中进行检查,这是一个昂贵的过程。
一种方法是使用范围。
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
validate_uniqueness_of :physician_id, scope: :patient_id
end
这将确保不允许同时复制两个ID的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.