60

In Rails 2, will removing a column with a Rails migration also change/remove indexes associated with the column? If not, and instead you have to also change/remove each index manually, shouldn't it instead be automated?

Thanks (from a Rails newbie)

Dexygen
  • 12,287
  • 13
  • 80
  • 147
  • By the way here's an interesting post that does not necessarily directly answer my question however: http://keyj.wordpress.com/2009/05/28/remove-index-with-rails-migrations/ – Dexygen Aug 26 '11 at 12:28
  • 8
    Update: currently, it does remove the index (Rails 4.1.7). – B Seven Nov 29 '14 at 16:38

6 Answers6

81

From Rails 4 upwards, the index removes automatically with the column removal.

x6iae
  • 4,074
  • 3
  • 29
  • 50
enter08
  • 943
  • 1
  • 8
  • 11
  • 5
    Although removing column will remove its index, it won't be fully reversible. Rollback will not add the index back. In this case `remove_index` is needed – Peter T. May 24 '19 at 09:02
27

No, unfortunately you have to remove the index manually from within your migration using the remove_index method.

John Topley
  • 113,588
  • 46
  • 195
  • 237
  • 7
    for MySQL 5.1 (at least) this does not appear to be the case. See: http://stackoverflow.com/a/4341928/ – Tyler May 10 '13 at 23:33
  • 6
    In Rails 4 it does now: http://stackoverflow.com/a/27622694/407213 (e.g.: I tried and after `remove_column ...`, `remove_index ...` throws a "Index name '...' on table '...' does not exist" <3 ) – Dorian Jun 16 '16 at 17:50
7

To clarify, inside a migration the syntax to remove a 2 column index is the following

remove_index :actions, :column => [:user_id,:action_name]

or by name, a worse option from my point of view

remove_index :actions, :name => "index_actions_on_user_id_and_action_name"
Maragues
  • 37,861
  • 14
  • 95
  • 96
6

Just as a caution, while Rails 4 will remove the index for you if you remove the column, you should specify the column type. Without a column type, running rake db:rollback will return

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

remove_column is only reversible if given a type.

I was experimenting with dropping foreign key columns that were indexed. Even specifying index: true in the change block didn't seem to make the columns reversible on rollback.

Jim
  • 400
  • 4
  • 17
1

If you want to remove index you should use remove_index, if you use remove_column it does remove the index but you can't run rake db:rollback. As Jim mentioned.

remove_column is only reversible if given a type.
William Hu
  • 15,423
  • 11
  • 100
  • 121
0

In Rails > 3.2.16, removing the column removes the index.

Mark Swardstrom
  • 17,217
  • 6
  • 62
  • 70