Rails Migration Error w/ Postgres when pushing to Heroku Rails Migration Error w/ Postgres when pushing to Heroku postgresql postgresql

Rails Migration Error w/ Postgres when pushing to Heroku


Same as above but a little bit more concise:

change_column :yourtable, :column_to_change, 'integer USING CAST("column_to_change" AS integer)'


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.