带有 2 个尾随数字的十进制数的迁移
Migration with a decimal number with 2 trailing digits
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 位的小数。
当我 运行 迁移并查看 table 结构时,我看到以下内容:
pre_tax_total decimal(10,0)
post_tax_total decimal(10,0)
这意味着值正在 运行 由 MySQL 服务器处理。将这些列创建为 decimal(10,2) 的 ActiveRecord 语法是什么?
那就是:
t.decimal :pre_tax_total, precision: 10, scale: 2
虽然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).
最后一行部分解释了为什么你得到 decimal(10,0)
。
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 位的小数。
当我 运行 迁移并查看 table 结构时,我看到以下内容:
pre_tax_total decimal(10,0)
post_tax_total decimal(10,0)
这意味着值正在 运行 由 MySQL 服务器处理。将这些列创建为 decimal(10,2) 的 ActiveRecord 语法是什么?
那就是:
t.decimal :pre_tax_total, precision: 10, scale: 2
虽然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).
最后一行部分解释了为什么你得到 decimal(10,0)
。