Reversible integer to string migrations in Rails
I recently needed to convert an integer column in Rails to a string, and wanted to make sure that the migration would be reversible. I specified the up
and down
methods, but found that I couldn't reverse the migration because the column type couldn't be automatically cast back into an integer.
As it turns out, Rails allows us to specify how to cast the column with the using
option:
def up
change_column :users, :zip, :string
end
def down
change_column :users, :zip, :integer,
using: "zip::integer"
end
This builds the sql:
ALTER TABLE users
ALTER COLUMN zip
TYPE integer
USING zip::integer
Good to go!
Tweet