I have a database-table cost with the columns amount and currency. I search for a solution to save a currency into this column.
What do you suggest: Which data type for the column currency and what values should I save there (iso-code, currency symbol ...)? Or maybe there is already a data type Currency in ruby like in java?
In general, you save the amounts as integers, because floating point are known to have rounding errors that are definitely not suitable for representing money.
Because money can have fractions, it's quite common that the integer represents the amount in cent, so that you can easily perform operations on the amounts, then divide by /100
to get the value as dollars.
The money
gem is the most popular library in Ruby to deal with currencies and money. Internally, the library uses exactly the same approach I just described. Actually, the library was moved in the past to use BigDecimal which are a Ruby-specific library for dealing with arbitrary precision integer arithmetic.
If you want to use it in Rails, the money-rails
gem is a quick solution. However, you are not required to use this gem, nor the money
gem, especially if your need is limited to that specific model and basic operations.
It's your choice. However, you should really represent amounts in integers. As for currencies, you can use simple varchar fields and use the 3-char standard representation.