2011-05-04 66 views

回答

2

模型中的自定義驗證是在我看來,最徹底的方法:

class Model 
    validate :at_least_one_present 

    def at_least_one_present 
    if(they_dont_exist) 
     errors.add("need at least one of these fields") 
    end 
    end 
end 

參考:Creating custom validation methods

3

您需要爲此編寫自定義驗證程序。所有你需要做的是子類ActiveModel::Validator和實施validate(record)方法,從而增加了記錄的errors散在發生錯誤的情況下:

class YourValidator < ActiveModel::Validator 
    def validate(record) 
     if (your_failure_condition_here) 
      record.errors[:base] << "Your error message" 
     end 
    end 
end 

,然後在模型中使用驗證器像這樣(假設你適當地加載你的驗證器類):

class YourModel 
    validates_with YourValidator 
end