Finding Your Existing Indexes in Rails (ActiveRecord) Published July 05, 2016

Awhile back, I had some Rails migrations go awry on a project I was working on. If I remember correctly, indexes were created on different git branches and it caused some confusion as to what indexes existed when we went to merge the branches. Getting these indexes is actually pretty easy. If you have a users table that you want to inspect for indexes, run:

> ActiveRecord::Base.connection.indexes("users").each{ |index| puts index.inspect }
#<struct ActiveRecord::ConnectionAdapters::IndexDefinition table="users", name="index_users_on_email", unique=true, columns=["email"], lengths=[], orders={}>
#<struct ActiveRecord::ConnectionAdapters::IndexDefinition table="users", name="index_users_on_user_type", unique=false, columns=["user_type"], lengths=[], orders={}>

Notice here that my users table contained two indexes: index_users_on_email, and index_users_on_user_type.

Getting the indexes of all tables isn't difficult either, but we'll format the output to be more readable given size of the potential output:

ActiveRecord::Base.connection.tables.each do |table|
  puts "#{table.capitalize}:"
  ActiveRecord::Base.connection.indexes(table).each do |index|
    puts "\tcolumns: #{index.columns}, name: #{index.name}, unique: #{index.unique}"
  end
end

You could also get the lengths and orders attributes from each index too, but I excluded them here since I don't need them.

Your output should look something like this:

# (...)
Users:
    columns: ["email"], name: index_users_on_email, unique: true
    columns: ["user_type"], name: index_users_on_user_type, unique: false
# (...)

This code has been tested on Rails 3.2, Rails 4, Postgres, and Sqlite.

Happy Coding. :)

rails
databases