🖥

#Rails migration / Remove unique index / Mysql2::Error: Cannot drop i

2020/01/19に公開

I dont know its best way or wrong way
but it seems to work

model Annotation = DB table schema info

Wanna delete UNIQUE index

# == Schema Information
#
# Table name: books
# user_id                          :bigint           not null
#
# Indexes
#
- # index_books_on_user_id (user_id)
+ # index_books_on_user_id (user_id) UNIQUE
#
#
# Foreign Keys
#  fk_rails_...  (user_id => sims.id)
#

Model

class Book < ApplicationRecord
  belongs_to :user
end

Fail Migration

class RemoveUniqueIndexUserIdFromBoook < ActiveRecord::Migration[5.2]
  def change
    # Mysql2::Error: Cannot drop index 'index_books_on_user_id': needed in a foreign key constraint
    remove_index :books, :user_id
  end
end

Succeed Migration

class RemoveUniqueIndexUserIdFromBoook < ActiveRecord::Migration[5.2]
  def change
    # Anti migration error
    # Mysql2::Error: Cannot drop index 'index_books_on_user_id': needed in a foreign key constraint
    remove_foreign_key :books, name: "fk_rails_80340687ab"
    remove_index :books, :user_id
    add_index :books, :user_id
    add_foreign_key :books, :users
  end
end

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2950

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2020-01-19

Discussion