2013-10-20 100 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的記錄將不被允許。