To avoid floating point issues, I’ve decided to store monetary values in
cents in the database. However, the user will enter these in dollars
and cents. Two questions:
How do I do the validation for the currency format? It looks like
ActiveRecord truncates the cents since it thinks the field type is a
Fixnum. Am I forced to do validation in the controller?
Where is the appropriate place to do the conversion from dollars to
cents? I initially was thinking of doing the conversion in
before_create or before_update, but again, it seems like the value is
truncated as described above.
To avoid floating point issues, I’ve decided to store monetary values in
cents in the database. However, the user will enter these in dollars
and cents. Two questions:
How do I do the validation for the currency format? It looks like
ActiveRecord truncates the cents since it thinks the field type is a
Fixnum. Am I forced to do validation in the controller?
Where is the appropriate place to do the conversion from dollars to
cents? I initially was thinking of doing the conversion in
before_create or before_update, but again, it seems like the value is
truncated as described above.
Here’s what I do for conversion:
def amount=(new_amount)
write_attribute(“amount”, (new_amount.to_f * 100.0).to_i)
end
def amount
read_attribute(“amount”).to_f / 100.0
end
I’m not quite sure what I’d validate about it, though:-)