Rails 4 迁移:如何重新排序列 [英] Rails 4 migration: how to reorder columns

查看:24
本文介绍了Rails 4 迁移:如何重新排序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到 add_column 有一个 :after 选项来设置列的插入位置.太糟糕了,我知道了:添加一堆之后.

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?

推荐答案

在使用 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)

这篇关于Rails 4 迁移:如何重新排序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆