25
Rails 3.2
MySQL gem

I have the following in my migration:

t.decimal :pre_tax_total, default: nil, scale: 2
t.decimal :post_tax_total, default: nil, scale: 2

Based on what I read, scale:2 will produce a decimal with 2 trailing digits.

When I run the migration, and look at the table structure, I see the following:

pre_tax_total   decimal(10,0) 
post_tax_total  decimal(10,0)

Which means the values are getting truncated by the MySQL server. What is the ActiveRecord syntax to create these columns as decimal(10,2)?

EastsideDev
  • 6,257
  • 9
  • 59
  • 116

2 Answers2

58

That would be:

t.decimal :pre_tax_total, precision: 10, scale: 2

Although Rails 3 Migrations Guide skips it, the description is available in the source code:

  # Note: The precision is the total number of significant digits,
  # and the scale is the number of digits that can be stored following
  # the decimal point. For example, the number 123.45 has a precision of 5
  # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can
  # range from -999.99 to 999.99.
  #
  # Please be aware of different RDBMS implementations behavior with
  # <tt>:decimal</tt> columns:
  # * The SQL standard says the default scale should be 0, <tt>:scale</tt> <=
  #   <tt>:precision</tt>, and makes no comments about the requirements of
  #   <tt>:precision</tt>.
  # * MySQL: <tt>:precision</tt> [1..63], <tt>:scale</tt> [0..30].
  #   Default is (10,0).

The last line partly explains why you got decimal(10,0).

Nic Nilov
  • 5,056
  • 2
  • 22
  • 37
  • It worked. Thank you. I could swear that the doc said that you could skip the precision param – EastsideDev Jul 19 '16 at 22:17
  • 4
    And you can do this through the command line generator with `rails g migration add_pre_tax_total_to_your_table_name pre_tax_total:decimal{10-2}`. – Joshua Pinter Dec 29 '18 at 21:14
0

Rails 4.0 and above supports generating migration with decimal precision and scale.

bin/rails generate migration AddPriceToProducts 'price:decimal{5,2}'

vishless
  • 829
  • 1
  • 5
  • 28