Search code examples
ruby-on-railsdatabasesqliteindexingrails-migrations

"SQLite3::SQLException: index already exists", but I can't find the index anywhere (Rails)


Trying to use a migration to create a joint table in Rails, but it's raising a exception about duplicate index.

How can I solve this supposedly duplicated index?

I tried to find this index by using queries like:

SELECT name FROM sqlite_master WHERE type='index';

No matching index was found;

The exception looks like this:

SQLite3::SQLException: index index_orders_clients_rental_cars_on_rental_car_id already exists
rails_project/db/migrate/20240827182356_create_join_table_orders_clients_rental_cars.rb:3:in `change'

Finally, this is the migration I'm trying to run:

class CreateJoinTableOrdersClientsRentalCars < ActiveRecord::Migration[7.1]
  def change
    create_table :orders_clients_rental_cars do |t|
      t.references :client, null: false, foreign_key: true
      t.references :rental_car, null: false, foreign_key: true
      t.datetime :rented_at
      t.datetime :updated_at
      t.datetime :expected_return
      t.datetime :returned_at, null: true

      t.index [:client_id, :rental_car_id], unique: true
      t.index :rental_car_id
    end
  end
end

Solution

  • The index is already created when using references, a foreign key constraint is also added when using foreign_key but the index is created regardless (unless you pass index: false).

    ActiveRecord::ConnectionAdapters::SchemaStatements#add_reference:

    The options hash can include the following keys:

    :index
    Add an appropriate index. Defaults to true. See add_index for usage of this option.

    This means you can remove, t.index :rental_car_id, and your index will still exist.