ActiveRecord列无法自动转换为数字类型

Sev*_*rin 2 postgresql activerecord ruby-on-rails type-conversion

我需要将DB中列的数据类型从:string更改为:decimal.所有值都采用以下格式:"129.99"因此转换它们不应引发任何错误.

为此,我写了以下迁移:

def change
  change_column :my_table, :target_column, :decimal
end
Run Code Online (Sandbox Code Playgroud)

当我执行它时,它向我显示以下错误以及如何修复它的提示:

PG::DatatypeMismatch: ERROR:  column "target_column" cannot be cast automatically to type numeric
HINT:  You might need to specify "USING target_column::numeric".
Run Code Online (Sandbox Code Playgroud)

但是,我似乎无法找到有关如何执行此操作的任何文档,因此提示并不能帮助我.

什么是执行此迁移的最佳方式?

Vao*_*sun 9

这应该做:

def change
  change_column :my_table, :target_column, 'numeric USING CAST(target_column AS numeric)'
end
Run Code Online (Sandbox Code Playgroud)


Nem*_*ion 5

对于只想更改列类型而不关心该字段中的数据会发生什么的人。

只需删除该列,然后使用正确的类型重新创建它:

def change
    remove_column :table_name, :field
    add_column :table_name, :field, :type
end
Run Code Online (Sandbox Code Playgroud)