Rails-column "price" cannot be cast automatically to type integer

上下文

想把price数据类型由string 改为integer

class ChangePriceTypeInUsers < ActiveRecord::Migration[5.0]
  def up
    change_column :users, :price, :integer

  end

  def down
    change_column :users, :price, :string
  end
end

在本地执行rails db:migrate时没出错(奇怪),在Heroku执行时出错。

线索

  1. 报错
    PG::DatatypeMismatch: ERROR: column "column_name" cannot be cast automatically to type integer HINT: Specify a USING expression to perform the conversion.

过程

谷歌搜column "column_name" cannot be cast automatically to type integer
在StackOverflow找打一个合适的解决办法,原文在这里

结果

原来是string类型不能直接转成integer。缺乏数据库知识。改后的代码为

class ChangePriceTypeInUsers < ActiveRecord::Migration[5.0]
  def up
    change_column :users, :price, 'integer USING CAST(price AS integer)'

  end

  def down
    change_column :users, :price, :string
  end
end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容