当推送到Heroku时,Rails迁移错误w / Postgres

时间:2012-09-26 14:01:00

标签: ruby-on-rails postgresql heroku rails-migrations

我正在尝试执行以下向上迁移,以更改“推文”模型表中的“数字”列

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

非常感谢您的任何想法。

谢谢大家。

2 个答案:

答案 0 :(得分:46)

与上述相同,但更简洁:

change_column :yourtable, :column_to_change, 'integer USING CAST("column_to_change" AS integer)'

答案 1 :(得分:32)

来自fine manual

  

[ALTER TABLE ... ALTER COLUMN ...]
  可选的USING子句指定如何从旧的计算新列值;如果省略,则默认转换与从旧数据类型转换为new的赋值相同。如果没有从旧类型到新类型的隐式或赋值转换,则必须提供USING子句。

PostgreSQL中没有从varcharint的隐式转换,所以它抱怨column "number" cannot be cast to type integer并且ALTER TABLE失败。您需要告诉PostgreSQL如何将旧字符串转换为数字以匹配新列类型,这意味着您需要在ALTER TABLE中获取USING子句。我不知道有什么方法可以让Rails为你做到这一点,但你可以轻松地手工完成:

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

你会想要注意无法转换为整数的值,PostgreSQL会告诉你是否有问题,你必须在迁移成功之前修复它们。

您现有的向下迁移应该没问题,将integer转换为varchar应该会自动处理。

相关问题