Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 migration: how to reorder columns

I learned that add_column has an :after option to set where the column gets inserted. Too bad I learned about it :after adding a bunch.

How can I write a migration to simply reorder columns?

like image 728
emersonthis Avatar asked Sep 19 '13 15:09

emersonthis


People also ask

Can you edit a migration file Rails?

Occasionally you will make a mistake when writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.

How do I redo a migration in Rails?

You must rollback the migration (for example with bin/rails db:rollback ), edit your migration, and then run bin/rails db:migrate to run the corrected version.

How do I down a specific migration in Rails?

To run a specific migration up or down, use db:migrate:up or db:migrate:down . The version number in the above commands is the numeric prefix in the migration's filename.


1 Answers

When using MySQL, you can call change_column, but you have to repeat the column type (just copy and paste it from your other migration):

def up
  change_column :your_table, :some_column, :integer, after: :other_column
end

Or if you have to reorder multiple columns in one table:

def up
  change_table :your_table do |t|
    t.change :some_column, :integer, after: :other_column
    # ...
  end
end

change_column calls ALTER TABLE under the hood. From the MySQL documentation:

You can also use FIRST and AFTER in CHANGE or MODIFY operations to reorder columns within a table.

Note that this approach doesn't work with PostgreSQL. (see Alter column positions)

like image 137
Stefan Avatar answered Sep 23 '22 13:09

Stefan