Ruby on Rails’s ActiveRecord supports the normal decimal SQL data type, with support for both precision and scale options. Unfortunately these two options are simple enough to understand, but similar enough to confuse.

In short, precision is the total number of digits in the decimal number, while scale is the number of digits to the right of the decimal place. Thus, the following migration:

1
2
3
4
5
6
7
8
9
10
class CreateNumbersTable < ActiveRecord::Migration
  def up
    create_table :numbers do |t|
      t.decimal :decimal_number, precision: 6, scale: 2
    end
  end

  def down
  end
end

creates a numbers table with a decimal_number column that will accept data in a X,XXX.XX format. Try to insert a number with more digits (say, 10,000.00) and it will give you an out-of-range error (as I wrestled with last night.)

H/T to Jtanium’s post for making this clear for me.

Comments