使用带有2个尾随数字的十进制数进行迁移

时间:2016-07-19 21:53:06

标签: ruby-on-rails activerecord rails-migrations

Rails 3.2
MySQL gem

我的迁移中有以下内容:

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

根据我读到的内容,scale:2将产生一个带有2个尾随数字的小数。

当我运行迁移并查看表结构时,我看到以下内容:

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

这意味着MySQL服务器会截断这些值。将这些列创建为十进制(10,2)的ActiveRecord语法是什么?

1 个答案:

答案 0 :(得分:19)

那将是:

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

虽然Rails 3 Migrations Guide跳过它,但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).

最后一行部分解释了为什么你得到decimal(10,0)