使用Rails迁移删除列将删除与该列关联的索引

Geo*_*pty 48 ruby-on-rails rails-migrations

在Rails 2中,删除带有Rails迁移的列还会更改/删除与列关联的索引吗?如果没有,而且您还必须手动更改/删除每个索引,那么它是否应该自动化?

谢谢(来自Rails新手)

小智 58

从Rails 4开始,索引会在删除列时自动删除.

  • 虽然删除列会删除其索引,但它不会完全可逆。回滚不会将索引添加回来。在这种情况下,需要 `remove_index` (4认同)

Joh*_*ley 25

不,遗憾的是,您必须使用该remove_index方法从迁移中手动删除索引.

  • 对于MySQL 5.1(至少),似乎并非如此.请参阅:http://stackoverflow.com/a/4341928/ (7认同)
  • 在Rails 4中它现在可以:http://stackoverflow.com/a/27622694/407213(例如:我尝试过`remove_column ...`,`remove_index ...`抛出一个"索引名称'......'在桌子上'......'不存在"<3) (5认同)

Mar*_*ues 6

为了澄清,在迁移内部,删除2列索引的语法如下

remove_index :actions, :column => [:user_id,:action_name]
Run Code Online (Sandbox Code Playgroud)

或者从我的角度来看,这是一个更糟糕的选择

remove_index :actions, :name => "index_actions_on_user_id_and_action_name"
Run Code Online (Sandbox Code Playgroud)


Jim*_*Jim 5

同样谨慎,如果删除列,Rails 4 将为您删除索引,您应该指定列类型.没有列类型,rake db:rollback将返回运行

rake aborted!
StandardError: An error has occurred, all later migrations canceled:

remove_column is only reversible if given a type.
Run Code Online (Sandbox Code Playgroud)

我正在尝试删除索引的外键列.即使index: true在更改块中指定,也不会使列在回滚时可逆.