Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Rails Migrations to delete an index without knowing its name

I have a table with a compound index that wasn't created through a rails migration. Now, I need to create a rails migration that will delete this index and create a new one, but I don't necessarily know what the name of the index will be.

I know that it is possible to get a list of table names and column names within a migration step. Is it possible to get a list of index names on a particular table? Or, looking at it another way, is it possible to delete all indexes on a table? Or is the only option to write my own database-specific SQL queries to get this info?

like image 618
bnsmith Avatar asked Aug 26 '09 13:08

bnsmith


2 Answers

You can get details of all the indexes on a table with:

ActiveRecord::Base.connection.indexes('tablename')

This returns an array of ActiveRecord::ConnectionAdapters::IndexDefinition objects, each of which has a #name and #columns method.

like image 106
showaltb Avatar answered Sep 20 '22 22:09

showaltb


To expand on @showaltb's great answer, here is a complete migration to remove all indexes on a table, without knowing their names:

ActiveRecord::Base.connection.indexes('tablename').each do |index|
  remove_index 'tablename', name: index.name
end
like image 30
Justin Tanner Avatar answered Sep 19 '22 22:09

Justin Tanner