我正在try 执行后续迁移,以更改"tweet"模型表中的"number"列

class ChangeDataTypeForTweetsNumber < ActiveRecord::Migration
  def up
    change_column :tweets do |t|
      t.change :number, :integer
    end
  end

  def down
    change_table :tweets do |t|
      t.change :number, :string
    end
  end
end

在执行到heroku的后续迁移时....

heroku rake db:migrate:up VERSION=20120925211232

我得到以下错误

    PG::Error: ERROR:  column "number" cannot be cast to type integer
: ALTER TABLE "tweets" ALTER COLUMN "number" TYPE integer

如果您有任何 idea ,我们将不胜感激.

谢谢大家.

推荐答案

fine manual人中:

[ALTER TABLE…ALTER COLUMN…]

PostgreSQL中没有从varcharint的隐式转换,因此它抱怨column "number" cannot be cast to type integer和ALTER表失败.您需要告诉PostgreSQL如何将旧字符串转换为数字以匹配新的列类型,这意味着您需要在ALTER表中获得USING子句.我不知道有什么方法可以让Rails为您做到这一点,但您可以很容易地用手做到:

def up
  connection.execute(%q{
    alter table tweets
    alter column number
    type integer using cast(number as integer)
  })
end

您需要注意不能转换为整数的值,PostgreSQL会告诉您是否存在问题,您必须在迁移成功之前修复这些问题.

现有的向下迁移应该可以,integervarchar的转换应该会自动处理.

Postgresql相关问答推荐

在Postgres游标中从一行变量中减go 另一行变量

如何判断上次在 TimescaleDB 上运行连续聚合作业(job)的时间

从 PostgreSQL 中的每个组中抽取 N 个样本

订阅标签保存在哪个表中?

在 PostgreSQL 中 Select 数字命名列会返回 ?column?

有对(type_id,element_id),如(1,1),(1,2),..(5,3).如果我需要获取没有 element_id 1 的类型 ID,如何从结果中排除 type_id?

如何从 .sql postgresql 备份恢复单个表?

Nodejs应用程序的node-postgres vs pg-promise

?(问号)运算符在 Rails 中查询 Postgresql JSONB 类型

在 row_to_json 函数中 Select 查询

从time without time zone和时区名称中获取time with time zone

使用 Hibernate 查询:colon gets treated as parameter / escaping colon

如何为 postgres 连接设置 application_name?

在 Postgresql 中按窗口函数结果过滤

根据 Helm 图表设置值

PostgreSQL 中跨多个表的索引

在 postgres 中存在不同的 string_agg 问题

当从 Heroku pg:pull 数据库时提示:role "root" does not exist.

PostgreSQL 字符串(255) 限制 - Rails、Ruby 和 Heroku

如何在不丢失openproject数据的情况下将postgresql数据库从10升级到12