Data transformation after successful validation
-
08-10-2019 - |
Pergunta
I'm having a bit of a problem normalizing a UPC string code so that I can store it in the same format in the database.
I'm using the ean
gem to check if the string is good (which is working fine), but if I throw some assignment code after it validates such as:
validate :upc_check
def upc_check
if !upc.nil?
if !upc.ean?
errors.add(:upc, 'is not a valid UPC.')
else
upc = upc.strip
end
end
end
The strip call is just an example as it's a string. I'll actually be removing the dashes in the upc.
The above code doesn't work so well as it doesn't actually save it. I had a look at triggering a method like
after_validation :normalize_upc
def normalize_upc
upc = upc.strip
end
..but the above doesn't work either.
What do you guys do to validate and transform data after validation?
Solução
I would make my validator strict, and then use a before_validation filter to do any necessary transformations.
Outras dicas
I would recommend overriding the setter method in your model for upc and not having a separate method for normalizing it. This would be accomplished with something like:
def upc=(value)
self.upc = value.strip
end
Edit:
I would also clean up your validation method to remove this functionality like so:
validate :upc_check, :unless => lambda {|m| m.upc.nil?}
def upc_check
errors.add(:upc, 'is not valid') unless upc.ean?
end