我需要你帮助验证一个简单的Rails模型。
首先,我想检查用户是否填写了所有输入字段:
class Test < ActiveRecord::Base
validates :firstname, :lastname, :firstvalue, :secondvalue, presence: true
[...]
我还想检查:secondvalue
参数是否大于:firstvalue
。
添加
validate :biggerThan
def biggerThan
if self.secondvalue < self.firstvalue
errors.add(:secondvalue, "must be bigger than First")
end
end
这是有效的,但只有填写了所有其他字段!创建一个新条目,将所有字段留空,我收到undefined method <' for nil:NilClass
。
你能帮帮我吗?
答案 0 :(得分:2)
你可以这样做
validate :biggerThan, if: Proc.new{ |test| test.firstvalue.present? and test.secondvalue.present? }
如果您同时添加numericality
验证
validates :firstvalue, numericality: true
validates :secondvalue, numericality: true