推送到 Heroku 时,带有 Postgres 的 Rails 迁移错误 [英] Rails Migration Error w/ Postgres when pushing to Heroku

查看:19
本文介绍了推送到 Heroku 时,带有 Postgres 的 Rails 迁移错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to perform the following up migration to change the column "number" in the "tweet" model's table

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....

Upon performing the the following up migration to 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

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

Any thoughts you have would be very much appreciated.

谢谢大家.

推荐答案

来自 精细手册:

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

[ALTER TABLE ... ALTER COLUMN ...]
The optional USING clause specifies how to compute the new column value from the old; if omitted, the default conversion is the same as an assignment cast from old data type to new. A USING clause must be provided if there is no implicit or assignment cast from old to new type.

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

There is no implicit conversion from varchar to int in PostgreSQL so it complains that column "number" cannot be cast to type integer and the ALTER TABLE fails. You need to tell PostgreSQL how to convert the old strings to numbers to match the new column type and that means that you need to get a USING clause into your ALTER TABLE. I don't know of any way to make Rails do that for you but you can do it by hand easily enough:

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

您需要注意无法转换为整数的值,PostgreSQL 会通知您是否存在问题,您必须在迁移成功之前修复它们.

You'll want to watch out for values that can't be cast to integers, PostgreSQL will let you know if there are problems and you'll have to fix them before the migration will succeed.

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

Your existing down-migration should be fine, converting integer to varchar should be handled automatically.

这篇关于推送到 Heroku 时,带有 Postgres 的 Rails 迁移错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆