Rails Migrations: tried to change the type of column from string to integer Rails Migrations: tried to change the type of column from string to integer ruby ruby

Rails Migrations: tried to change the type of column from string to integer


I quote the manual about ALTER TABLE:

A USING clause must be provided if there is no implicit or assignment cast from old to new type.

What you need is:

ALTER TABLE listings ALTER longitude TYPE integer USING longitude::int;ALTER TABLE listings ALTER latitude  TYPE integer USING latitude::int;

Or shorter and faster (for big tables) in one command:

ALTER TABLE listings ALTER longitude TYPE integer USING longitude::int                    ,ALTER latitude  TYPE integer USING latitude::int;

This works with or without data as long as all entries are convertible to integer.
If you have defined a DEFAULT for the column, you may have to drop and recreate that for the new type.

Here is blog article on how to do this with ActiveRecord.
Or go with @mu's advice in the comment. He knows his Ruby. I am only good with the PostgreSQL here.


I know this a bit ugly, but I prefer to just remove the column and add again with the new type:

 def change     remove_column :mytable, :mycolumn     add_column :mytable, :mycolumn, :integer, default: 0 end


I would include the raw SQL in your migration file like below so that it updates schema.rb.

class ChangeColumnType < ActiveRecord::Migration  def up    execute 'ALTER TABLE listings ALTER COLUMN latitude TYPE integer USING (latitude::integer)'    execute 'ALTER TABLE listings ALTER COLUMN longitude TYPE integer USING (longitude::integer)'  end  def down    execute 'ALTER TABLE listings ALTER COLUMN latitude TYPE text USING (latitude::text)'    execute 'ALTER TABLE listings ALTER COLUMN longitude TYPE text USING (longitude::text)'  endend