推送到 Heroku 时,带有 Postgres 的 Rails 迁移错误

编程入门 行业动态 更新时间:2024-10-24 01:52:59
本文介绍了推送到 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 中没有从 varchar 到 int 的隐式转换,所以它抱怨 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 迁移错误

本文发布于:2023-10-17 10:30:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500655.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:错误   Heroku   Postgres   Rails

发布评论

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

>www.elefans.com

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