Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails error: Index name '...' on table '...' already exists while running rails db:migrate

So I'm working with a colleague who added some additional migration files and per normal procedure once I pulled their version I ran rails db:migrate. I end up getting the following errors:

 Index name 'index_authorizations_on_user_id' on table 'authorizations' already exists

 ArgumentError: Index name 'index_authorizations_on_user_id' on table 'authorizations' already exists

So I went and checked the schema and the table is already present. So why is it failing? Typically in the past it only generates new table entries/updates when doing a migration so why isn't it just ignoring it?

I've tried doing a rollback and get: This migration uses remove_columns, which is not automatically reversible.

I've tried doing bin/rails db:migrate RAILS_ENV=development and I get the same errors.

I've done a db:reset, db:drop, and it all comes back to an issue with pending migrations that I cannot get to run. What am I doing wrong?

They added the following migration: 20171024074328_create_authorizations.rb

 class CreateAuthorizations < ActiveRecord::Migration[5.1]
  def change
    create_table :authorizations do |t|
      t.string :provider
      t.string :uid
      t.references :user, foreign_key: true

      t.timestamps

      add_index :authorizations, :user_id
      add_index :authorizations, [:provider, :uid], unique: true
    end
  end

end

like image 709
Jake Avatar asked Oct 25 '17 15:10

Jake


1 Answers

This:

t.references :user, foreign_key: true

adds an index on authorizations.user_id for you. If you check the references documentation it will point you at add_reference and that says:

:index
Add an appropriate index. Defaults to true. [...]

So index: true is the default when you call t.references :user and that creates the same index that add_index :authorizations, :user_id creates.

like image 181
mu is too short Avatar answered Nov 16 '22 09:11

mu is too short