我想重构Date
字段
include Virtus.model
attribute :created_from, Date
attribute :created_to, Date
attribute :updated_from, Date
attribute :updated_to, Date
validate :validate_created_from_is_a_date, if: :created_from
validate :validate_created_to_is_a_date, if: :created_to
validate :validate_updated_from_is_a_date, if: :updated_from
validate :validate_updated_to_is_a_date, if: :updated_to
def validate_created_from_is_a_date
errors.add(:created_from, "not a date") unless created_from.is_a?(Date)
end
def validate_created_to_is_a_date
errors.add(:created_to, "not a date") unless created_to.is_a?(Date)
end
def validate_updated_from_is_a_date
errors.add(:updated_from, "not a date") unless updated_from.is_a?(Date)
end
def validate_updated_to_is_a_date
errors.add(:updated_to, "not a date") unless updated_to.is_a?(Date)
end
正如您所看到的,我有4个属性需要验证Date
我已经尝试了以下内容,但它无法检查所有情况
validate :validate_date_attributes, if: :any_date_attributes_defined?
def any_date_attributes_defined?
created_from || created_to || updated_from || updated_to
end
def validate_date_attributes
%w(created_from created_to updated_from updated_to).each do |attribute|
errors.add(attribute.to_sym, "not a date") unless attribute.to_sym.is_a?(Date)
end
end
答案 0 :(得分:1)
因此找到了处理此类案件的好方法,希望它对其他人有用:
validate :created_from, date_attribute: true, if: :created_from
validate :created_to, date_attribute: true, if: :created_to
validate :updated_from, date_attribute: true, if: :updated_from
validate :updated_to, date_attribute: true, if: :updated_to
将在DateAttributeValidator
查找
class DateAttributeValidator < ActiveModel::EachValidator
def validate_each(record, attr_name, value)
record.errors[attr_name] << "not a date" unless value.is_a?(Date)
end
end
我真的很喜欢它,非常整洁,它很干净,红宝石/轨道方式