Reputation: 10748
My model has:
validates :budget, :numericality => {:greater_than_or_equal_to => 0.01},
:presence => true,
:format => { :with => /^[$]?([0-9][0-9]?([,][0-9]{3}){0,4}([.][0-9]{0,4})?)$|^[$]?([0-9]{1,14})?([.][0-9]{1,4})$|^[$]?[0-9]{1,14}$/ }
but submitting a form with a value with a dollar sign or commas causes it to set :budget to 0.0
.
What's the best / cleanest way to accept values like $1,000
into this decimal column? (I format the output as currency, elsewhere, in a decorator).
Upvotes: 0
Views: 137
Reputation: 7344
If all you care to do is save the raw value, you can create a custom setter:
def budget= value
write_attribute :budget, value.scan(/[0-9]/).join.to_f
end
But if you plan to do more with currencies in your project, I would highly recommend checking out the money-rails gem. It gives you parsers, validators, arithmetic operators and much more to deal with currencies.
Upvotes: 1