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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With