1

I've searched high and low, but I could not find a solution, to what I think seems like a very common task.

In a form I want to have a text input that accepts currency strings (i.e. $1,000,000 or 1000 or $12.12 and in an ideal world even 1 million)

In the database I want to keep the value as a integer.

What is the best way to (a) validate that the input is a valid currency string, (b) when displaying the form, to display it formatted.

For date, i found the a great gem: validates_timeliness, which allows :

validates_date :my_date, :allow_blank => true

I would love to find a similar syntax for currency.

Thanks!

Jonathan
  • 15,639
  • 11
  • 63
  • 102
  • 1
    Why would you want to store 12.12 as an integer? – Jason Punyon Nov 06 '09 at 14:24
  • I have should have been more clear, currently I store my currency in the db as cents. But I am open to other suggestions. – Jonathan Nov 06 '09 at 14:50
  • Checkout this similar post on Stackoverflow: http://stackoverflow.com/questions/1019939/ruby-on-rails-best-method-of-handling-currency-money – Dave Nov 06 '09 at 15:05
  • Thanks Dave, I saw that, but I did not see where it handled converting the Currency string to a number. – Jonathan Nov 06 '09 at 15:09

1 Answers1

2

Check out rails_money. I think it does everything you need, including handling $ in the input fields and storing the value in cents. In fact, you just create your column as price_in_cents, and it does the rest.

Jonathan Julian
  • 11,973
  • 2
  • 40
  • 48