我有一个 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 在尝试使用空白属性进行计算时会引发错误。
那么如何首先检查所有必需属性的存在呢?