dou*_*ets 21 postgresql ruby-on-rails heroku rails-migrations
我正在尝试执行以下向上迁移以更改"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
Run Code Online (Sandbox Code Playgroud)
执行以下向上迁移到heroku ....
heroku rake db:migrate:up VERSION=20120925211232
Run Code Online (Sandbox Code Playgroud)
我收到以下错误
PG::Error: ERROR: column "number" cannot be cast to type integer
: ALTER TABLE "tweets" ALTER COLUMN "number" TYPE integer
Run Code Online (Sandbox Code Playgroud)
任何想法都会非常感激.
感谢大家.
ril*_*ley 46
与上面相同,但更简洁一点:
change_column :yourtable, :column_to_change, 'integer USING CAST("column_to_change" AS integer)'
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 32
从精细手册:
[ALTER TABLE ... ALTER COLUMN ...]
可选USING子句指定如何从旧计算新列值; 如果省略,则默认转换与从旧数据类型转换为new的赋值相同.一个USING如果从旧到新类型没有隐含或者赋值转换必须提供条款.
有一个从没有隐式转换varchar到intPostgreSQL中,因此抱怨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
Run Code Online (Sandbox Code Playgroud)
您需要注意无法转换为整数的值,PostgreSQL会告诉您是否存在问题,并且您必须在迁移成功之前修复它们.
您现有的向下迁移应该没问题,转换integer为varchar应该自动处理.
| 归档时间: |
|
| 查看次数: |
7411 次 |
| 最近记录: |