Rails 条件验证

Rails validations if condition

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