Rails迁移错误w / Postgres推向Heroku时 [英] Rails Migration Error w/ Postgres when pushing to Heroku
问题描述
我试图执行以下迁移操作来更改tweet模型表格中的数字列
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
执行以下向Herokuku的迁移....
Upon performing the the following up migration to heroku....
heroku rake db:migrate:up VERSION=20120925211232
我收到以下错误:
I get the following error
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.
谢谢每个人。
推荐答案
从精细手册:
[ALTER TABLE ... ALTER COLUMN。 ..]
可选的USING
子句指定如何从旧的计算新的列值;如果省略,则默认转换与从旧数据类型到新转换的赋值相同。如果没有隐式或赋值从旧类型转换为新类型,则必须提供USING
子句。
[ALTER TABLE ... ALTER COLUMN ...]
The optionalUSING
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. AUSING
clause must be provided if there is no implicit or assignment cast from old to new type.
在PostgreSQL中没有从 varchar
到 int
的隐式转换,所以它抱怨 columnnumber不能转换为整型
类型,并且ALTER TABLE失败。您需要告诉PostgreSQL如何将旧字符串转换为数字以匹配新的列类型,这意味着您需要在ALTER TABLE中获得USING子句。我不知道有什么方法可以让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.
这篇关于Rails迁移错误w / Postgres推向Heroku时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!