Rails迁移错误w / Postgres推向Heroku时

编程入门 行业动态 更新时间:2024-10-26 16:27:13
本文介绍了Rails迁移错误w / Postgres推向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 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中没有从 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时

本文发布于:2023-10-16 05:18:12,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   Rails   Heroku   Postgres

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!