hectorsq
hectorsq

Reputation: 76986

Is it possible to rename an index using a rails migration?

I know that there is a rename_column transformation, but it seems that rename_index does not exist.

Do I have to use remove_index and add_index instead?

Upvotes: 48

Views: 22591

Answers (5)

Nothus
Nothus

Reputation: 1167

rename_index should be given strings and not symbols when referencing the index name.

rename_index :table_name, 'old_name', 'new_name'

Had me scratching my head for a while when trying to rename a table and its indexes. Rails 3.2.3 and MySQL.

Upvotes: 78

Greg Blass
Greg Blass

Reputation: 3650

As of Rails 5 (EDIT: also in Rails 4), renaming the column will also automatically rename the index.

Upvotes: 29

Guillaume
Guillaume

Reputation: 705

Rails 3 provide a shortcut to rename an index:

rename_index :table_name, :old_name, :new_name

http://guides.rubyonrails.org/migrations.html

By the way, it doesn't do more than removing the old one and adding the new one:

http://apidock.com/rails/v2.3.8/ActiveRecord/ConnectionAdapters/SchemaStatements/rename_index

Upvotes: 45

Toby Hede
Toby Hede

Reputation: 37133

You can execute arbitrary SQL in your migrations as well.

We have some helper methods that add foreign keys to our tables:

def add_foreign_key(from_table, from_column, to_table)
  constraint_name = "fk_#{from_table}_#{from_column}"

  execute %{alter table #{from_table}
            add constraint #{constraint_name}
            foreign key (#{from_column})
            references #{to_table}(id)
           }
  end

You can use any SQL your database supports.

Upvotes: 1

netflux
netflux

Reputation: 3838

According to the API, using remove_index and add_index is the only way to achieve this.

Upvotes: 4

Related Questions