如果条件,Rails验证

时间:2015-03-12 11:11:02

标签: ruby-on-rails ruby-on-rails-4 conditional

我需要你帮助验证一个简单的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

你能帮帮我吗?

1 个答案:

答案 0 :(得分:2)

你可以这样做

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

如果您同时添加numericality验证

,那将是件好事
validates :firstvalue, numericality: true
validates :secondvalue, numericality: true