0

如何向 Rails 验证添加条件。例如,在进行其他验证之前检查是否所有字段都已填写。

4

1 回答 1

2

ActiveRecord 提供了一个回调选项before_validation,它允许方法在验证之前运行。

在您的模型中,添加

class XModel < ActiveRecord::Base
  ...
  before_validation :check_for_existence
  ...

  private

    def check_for_existence
      self.attributes.each do |attr|
        return false if self[attr].nil?
      end
    end
end

所以基本上,check_for_existence方法在所有其他验证之前被调用。check_for_existence方法遍历所有对象的属性并检查每个属性的值。如果其中任何一个是nil,则该方法将返回false并且所有以后的回调都将被取消,包括验证。

于 2013-09-07T07:50:59.993 回答