【问题标题】:ActiveRecord column cannot be cast automatically to type numericActiveRecord 列不能自动转换为数字类型
【发布时间】:2017-10-23 05:45:26
【问题描述】:

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

为此,我编写了以下迁移:

def change
  change_column :my_table, :target_column, :decimal
end

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

PG::DatatypeMismatch: ERROR:  column "target_column" cannot be cast automatically to type numeric
HINT:  You might need to specify "USING target_column::numeric".

但是,我似乎找不到任何有关如何执行此操作的文档,因此该提示并没有真正帮助我。

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

【问题讨论】:

  • 试试change_column :my_table, :target_column, 'numeric USING CAST(target_column AS numeric)'
  • @VaoTsun 工作,谢谢。如果你写一个正确的答案,我会接受。

标签: ruby-on-rails postgresql activerecord type-conversion


【解决方案1】:

应该这样做:

def change
  change_column :my_table, :target_column, 'numeric USING CAST(target_column AS numeric)'
end

【讨论】:

  • 注意:对于将来尝试转换具有类似问题的另一列的人,请记住输入 cast 字符串而不是 new_type 并将 numeric 替换为新类型。如果这不起作用,那么您的数据类型相距太远,您可能需要类似的东西:stackoverflow.com/a/54313334/10313894
【解决方案2】:

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

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

def change
    remove_column :table_name, :field
    add_column :table_name, :field, :type
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-28
    • 2023-03-28
    • 2015-07-26
    • 2022-09-25
    • 1970-01-01
    • 2015-10-12
    • 2016-10-16
    • 2010-12-01
    相关资源
    最近更新 更多