2011-05-04 67 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