且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails 4 迁移:如何重新排序列

更新时间:2023-11-23 14:50:46

在使用 MySQL 时,可以调用 change_column,但必须重复列类型(只需从其他迁移):

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 在后台调用 ALTER TABLE.来自 MySQL 文档:

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

您还可以在 CHANGEMODIFY 操作中使用 FIRSTAFTER 来重新排序表中的列.

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

请注意,这种方法不适用于 PostgreSQL.(请参阅更改列位置)

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