我需要您的帮助来验证简单的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
。
你可以帮帮我吗?
你可以这样做
validate :biggerThan, if: Proc.new{ |test| test.firstvalue.present? and test.secondvalue.present? }
如果您还添加numericality
验证,那就太好了
validates :firstvalue, numericality: true
validates :secondvalue, numericality: true
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句