Will removing a column with a Rails migration remove indexes associated with the column

Ruby on-RailsRails Migrations

Ruby on-Rails Problem Overview


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)

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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"

Solution 4 - Ruby on-Rails

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.

Solution 5 - Ruby on-Rails

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.

Solution 6 - Ruby on-Rails

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDexygenView Question on Stackoverflow
Solution 1 - Ruby on-Railsenter08View Answer on Stackoverflow
Solution 2 - Ruby on-RailsJohn TopleyView Answer on Stackoverflow
Solution 3 - Ruby on-RailsMaraguesView Answer on Stackoverflow
Solution 4 - Ruby on-RailsJimView Answer on Stackoverflow
Solution 5 - Ruby on-RailsWilliam HuView Answer on Stackoverflow
Solution 6 - Ruby on-RailsMark SwardstromView Answer on Stackoverflow