I have a custom validator that I want to apply to several attributes in the same model
right now I the following the works just fine:
validates :first_name, validator_name: true
validates :age, validator_name: true
validates :gender, validator_name: true
But when I try:
validates :first_name, :age, :gender, validator_name: true
The validator will run for the first attribute (:first_name) but not the others. Is this possible to achieve? I spent hours googling this but haven't found any examples
module Person
class SomeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return unless can_do_something?(record, attribute)
#... more code
end
def can_do_something?(record, attribute)
anything_new = record.new_record? || record.attribute_changed?(attribute)
end
end
end
Not sure if this should just be a comment or if it constitutes an answer; however what you are requesting...
...is how an
EachValidatorworks.So what you are describing...
..cannot be accurate.
For Example:
In this case all three attributes will be validated through the
StartsWithXValidator.e.g.
Working Example