2013-10-20 102 views
0

填充前检查我有两个型号医生和病人,象下面这样:轨道 - 通过模型

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 =病人OBJ。

所以,p.appointments.append(physican_obj)是正确的方法。 但是,如果我运行两次相同的命令,它将两次添加相同的东西。那么,在追加之前检查它是否已经存在是否好?什么是最好的方式来做到这一点?

我的要求是,我得到一个对象列表来添加它,所以我需要遍历每个对象并追加每个对象。如果在追加前需要检查,我需要检查每个循环,这是一个昂贵的过程。

回答

1

一种方法是使用范围。

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

    validate_uniqueness_of :physician_id, scope: :patient_id 
end 

这将确保一个重复两个id的记录将不被允许。