2011-01-12 112 views
2

我想知道我是否可以編寫驗證來驗證基於多個字段的記錄的唯一性。我的模型有一個複合主鍵,即如何使用ActiveRecord中的複合鍵驗證模型?

field :houseno, :type => String 
field :street, :type => String 
field :boro, :type => String 

什麼是驗證該記錄的唯一性的好辦法?

我試圖使用自定義的驗證這樣的:

class AddressValidator < ActiveModel::Validator 

    def validate(record) 
    record.errors[:base] << "This address is already in our records." unless check(record) 
    end 

    private 
    def check(record) 
     Address.find(:street=>record.street,:houseno=>record.houseno,:boro=>record.boro).length > 0 
    end 
end 

回答

10

工作的呢?

validates_uniqueness_of :houseno, :scope => [:street, :boro] 
+1

謝謝,這工作得很好。您還可以表示爲驗證:houseno,:length => {:minimum => 1,:maximum => 6,:allow_blank => false,:allow_nil => true},:uniqueness => {:scope => [:街道,:boro]} – Avishai 2011-12-21 16:48:48

相關問題