我有一个Rails模型,用户通过表单填写了其中的7个数字属性。
我需要验证每个属性是否存在,这显然很容易使用以下方法:
validates :attribute1, :presence => true
validates :attribute2, :presence => true
# and so on through the attributes
然而我还需要运行一个自定义验证器,它需要获取一些属性并对它们进行计算。如果这些计算的结果不在某个范围内,则应将模型声明为无效。
单独考虑这个问题也很容易。
validate :calculations_ok?
def calculations_ok?
errors[:base] << "Not within required range" unless within_required_range?
end
def within_required_range?
# check the calculations and return true or false here
end
问题在于“验证”方法总是在“校验”方法之前运行。这意味着,如果用户将所需字段中的任何一个留空,Rails 在尝试使用空白属性进行计算时会抛出错误。
那么,我该如何首先检查所有必需属性是否存在?