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

你可能感兴趣的:(Rails-column "price" cannot be cast automatically to type integer)