Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

ruby - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...