LoginSignup
0
0

More than 1 year has passed since last update.

#Rails migration / Remove unique index / Mysql2::Error: Cannot drop index 'index_xxx_on_yyy_id': needed in a foreign key constraint

Last updated at Posted at 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

チャットメンバー募集

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

Twitter

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0