Index Name too Long in Rails

Today I ran into the issue with creating an Index in Rails (the database being PostgreSQL). The migration looked something like this:

class AddIndex < ActiveRecord::Migration
  def up
    add_index :user_lists_show_case_items, [:user_list_id, :show_case_item_id], unique: true
  end

  def down
    remove_index :user_lists_show_case_items, [:user_list_id, :show_case_item_id]
  end
end

Which gave me this error:

Index name 'index_users_lists_show_case_items_on_user_list_id_and_show_case_item_id' on table 'user_lists_show_case_items' is too long; the limit is 63 characters

Luckily there’s an easy fix - we can specify the name of the index (more info over at APIdock).

class AddIndex < ActiveRecord::Migration
  def up
    add_index :user_lists_show_case_items, [:user_list_id, :show_case_item_id], unique: true, name: 'user_lists_show_case_items_unique'
  end

  def down
    remove_index :user_lists_show_case_items, name: 'user_lists_show_case_items_unique'
  end
end

Note the index name must be a string, not a symbol (as per APIdock). Happy coding.