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

时间:2011-02-21 16:58:03

标签: ruby-on-rails validation

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

  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

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

2 个答案:

答案 0 :(得分:3)

def self.validate_is_valid_datetime(field)
  validate do |model|
    if model.send("#{field}?") && ((DateTime.parse(model.send(field)) rescue ArgumentError) == ArgumentError)
      model.errors.add(field, 'must be a valid datetime')
    end
  end
end

validate_is_valid_datetime :datetime_field

答案 1 :(得分: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

<强> UPD

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

  validates :datetime_field, :another_datetime_field, :third_datetime_field, :presence => true, :date => true