Search This Blog

Saturday, December 4, 2010

Data transformation after successful validation

Programmer Question

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?



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails