Rails Migration Error w/ Postgres when pushing to

2019-01-18 02:30发布

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

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.

Thanks everyone.

2条回答
Luminary・发光体
2楼-- · 2019-01-18 03:14

From the fine manual:

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

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

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.

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

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-18 03:20

Same as above but a little bit more concise:

change_column :yourtable, :column_to_change, 'integer USING CAST("column_to_change" AS integer)'
查看更多
登录 后发表回答