Same user check for multiple fields in Rails

I have four date_time fields in my model in a Rails application. I want to apply the same verification method to them, so that only valid time can be accepted. The validation method is executed with an earlier question when the stack overflows:

  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

Is there a more elegant way to test these fields besides defining four exactly the same methods for each DateTime field?

+5
source share
2 answers

The best solution is to create your own validator:

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

you can use the same checks as follows:

  validates :datetime_field, :another_datetime_field, :third_datetime_field, :presence => true, :date => true
+3
source
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
+3
source

All Articles