LoginSignup
9
4

More than 3 years have passed since last update.

外部キー制約のついたカラムを削除したい

Last updated at Posted at 2020-03-16

外部キー制約の付いたカラムを削除するのにプチハマりしたのでまとめます

参考

こちらの記事でマイグレーションについてかなり詳しくまとめられています
マイグレーションの操作をするときは、こちらの記事で該当箇所をざっと読んでから公式ドキュメントに目を通すのが良さそう
https://pikawaka.com/rails/migration

例)ベストアンサー機能

  • questionモデル内に、ベストアンサーに選ばれた回答を保存するためのbestカラムがある
  • bestカラムには外部キーが設定してある(answersテーブル)

という状況

db/schema.rb
create_table "questions", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
  t.bigint "best"
  t.index ["best"], name: "fk_rails_dd35f91b0c"
end

add_foreign_key "questions", "answers", column: "best"

実践

まずはカラム削除用のマイグレーションファイルを作成する

$rails g migration RemoveBestFromQuestions

マイグレーションファイルが生成

db/migrate/xxxx_remove_best_from_questions.rb
class RemoveBestFromQuestions < ActiveRecord::Migration[5.1]
  def change
  end
end

こちらにカラムを削除するための記述を追加していく
外部キーとインデックスを貼っているので、カラムを削除する記述だけではエラーが発生してしまう
それらを削除する記述も必要っぽい

db/migrate/xxxx_remove_best_from_questions.rb

class RemoveBestFromQuestions < ActiveRecord::Migration[5.1]
  def change
    remove_foreign_key :questions, :answers
    remove_index :questions, :best
    remove_column :questions, :best, :bigint
  end
end

これでrails db:migrateを実行すればOK

最後に

間違っている部分があれば遠慮なくご指摘ください

9
4
1

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
9
4