Rails 4 migration: how to reorder columns

2019-02-01 21:36发布

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?

2条回答
贪生不怕死
2楼-- · 2019-02-01 22:08

Stefan's solution is perfect if you're dealing with just a handful of columns. If you have multiple columns to be re-arranged AND happen to be on a Mac, I suggest you take a look at Sequel Pro, a nifty database management tool that makes re-ordering database columns a breeze. Just drag and drop.

PS: I am not affiliated with them in any way.

查看更多
Bombasti
3楼-- · 2019-02-01 22:12

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.

查看更多
登录 后发表回答