44

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?

7
  • You could dump you Database to save the Data ; re-order your Schema.rb to put the timestamps columns at the end of the create_table's block ; run rake db:drop db:create db:migrate and then re-import your Data
    – MrYoshiji
    Sep 19, 2013 at 15:37
  • Now, that's an undocumented feature : You have to read core sources to find it. Just for reference, I've checked rename_column code : it does not offer this feature (sorry it doesn't help).
    – kik
    Sep 19, 2013 at 15:51
  • 1
    Use SQL in a migration. stackoverflow.com/questions/4095481/…
    – Zabba
    Sep 19, 2013 at 16:27
  • @Zabba That's not a bad idea. Could you submit it as an answer, preferably with some code to show the syntax for executing raw MySQL in a migration. Sep 19, 2013 at 16:30
  • I just pointed out another answer on SO, but Stefan shows a nice way to do it without SQL..
    – Zabba
    Sep 19, 2013 at 17:01

1 Answer 1

68

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)

8
  • Good catch. I was not aware it was doable through ALTER TABLE.
    – kik
    Sep 19, 2013 at 17:11
  • @OlivierElMekki I've added a link to the MySQL documentation
    – Stefan
    Sep 19, 2013 at 18:55
  • @Stefan Can I get away with using def change instead of up and down? Sep 19, 2013 at 19:27
  • 2
    @Emerson Rails currently can't reverse change_column. Do you really have to revert the column order?
    – Stefan
    Sep 19, 2013 at 19:49
  • 9
    None of this works with postgres- it's impossible to reorder columns stackoverflow.com/a/31683264/165673
    – Yarin
    Jan 23, 2016 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.