我觉得我在这里吃了疯狂的药。我有一个 MySQL 支持的 ActiveRecord 类,并且在 Rails 中将许多属性报告为 Integer 类型:
Device.last.score.class # returns `Fixnum`
MySQL 报告列的类型为 decimal(10,0)
。
我在这里错过了什么?甚至尝试调用 reset_column_information
。迁移看起来是正确的,模式文件看起来也不错。
注意:这个问题没有发生在我使用 SQLite 的开发中。
这是我的迁移:
class AddScoreColumnToDevices < ActiveRecord::Migration
def change
add_column :devices, :score, :decimal
end
end
最佳答案
迁移帮了我大忙!谢谢你!
新迁移的 :decimal
的默认值是 :precision => 0
和 :scale => 0
,这将导致MySQL decimal 不接受小数点后的任何内容。
Ruby 会将那个数字(小数点后没有任何内容)视为 Fixnum,这就是您所观察到的。
因此,您需要编写一个新的迁移来更改列并提供小数精度和小数位数 > 0。
change_column :devices, :score, :decimal, :precision => 10, :scale => 10
引用资料:
ActiveRecord ConnectionAdapter TableDefinition #column
decimal precision and scale
old reference on MySQL column<->Ruby datatype mapping
关于mysql - ActiveRecord 在 MySQL 中为 Decimal 时将属性视为 Integer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18772464/