将列类型更改为整数 Rails

3

我尝试在heroku上将表格列从字符串更改为整数,运行了迁移:

这是我的迁移文件:

class ChangePriceTypeInItems < ActiveRecord::Migration
  def change
    change_column :items, :price, :integer
  end
end

这是我的错误: 我该怎么做?
ActiveRecord::StatementInvalid: PG::Error: ERROR:  column "price" cannot be cast automatically to type integer
HINT:  You might need to specify "USING price::integer".
: ALTER TABLE "items" ALTER COLUMN "price" TYPE integer

1
它之前是什么类型?由于现有数据的存在,某些列类型无法自动转换为:integer - user896237
4个回答

11

其他答案是正确的,但你也可以使用:using关键字:

change_column :items, :price, :integer, using: 'price::integer'

1
如果你确定字符串列中的数据可以转换为整数,那么可以继续执行迁移操作并进行以下更改:
change_column :items, :price, 'integer USING CAST(price AS integer)'

1

1
class ChangePriceTypeInItems < ActiveRecord::Migration
  safety_assured

  def change
    # Take the back-up of your data first
    Item.update_all(price: nil)
    change_column :items, :price, :integer, using: 'price::integer'
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接