对Rails中的几个字段进行相同的自定义验证

Nik*_*kov 5 validation ruby-on-rails

我在Rails应用程序模型中有四个date_time字段.我想对它们应用相同的验证方法,以便只接受有效的日期时间.验证方法来自早期的堆栈溢出问题:

  validate :datetime_field_is_valid_datetime

  def datetime_field_is_valid_datetime
    errors.add(:datetime_field, 'must be a valid datetime') if ((DateTime.parse(datetime_field) rescue ArgumentError) == ArgumentError) && !datetime_field.nil? && !datetime_field.blank?
  end
Run Code Online (Sandbox Code Playgroud)

除了为每个DateTime字段定义四个完全相同的方法之外,还有更优雅的方法来验证这些字段吗?

fl0*_*00r 3

最好的解决方案是创建自己的验证器:

class MyModel < ActiveRecord::Base
  include ActiveModel::Validations

  class DateValidator < ActiveModel::EachValidator
    def validate_each(record, attribute, value)
      record.errors[attribute] << "must be a valid datetime" unless (DateTime.parse(value) rescue nil)
    end
  end
  validates :datetime_field, :presence => true, :date => true
  validates :another_datetime_field, :presence => true, :date => true
  validates :third_datetime_field, :presence => true, :date => true
end
Run Code Online (Sandbox Code Playgroud)

UPD

您可以通过这种方式共享相同的验证:

  validates :datetime_field, :another_datetime_field, :third_datetime_field, :presence => true, :date => true
Run Code Online (Sandbox Code Playgroud)