Rails验证(如果有条件)

马克斯沃斯

我需要您的帮助来验证简单的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

你可以帮帮我吗?

拉吉普·辛格(Rajdeep Singh)

你可以这样做

validate :biggerThan, if: Proc.new{ |test| test.firstvalue.present? and test.secondvalue.present? }

如果您还添加numericality验证,那就太好了

validates :firstvalue, numericality: true
validates :secondvalue, numericality: true

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章