我在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
解决方法
最佳解决方案是创建自己的验证器:
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,:date => true validates :third_datetime_field,:date => true end
UPD
您可以这样分享相同的验证:
validates :datetime_field,:another_datetime_field,:third_datetime_field,:date => true