LoginSignup
1
1

More than 3 years have passed since last update.

Rails:migrationで外部キー制約付きのカラムを追加(削除)する

Last updated at Posted at 2020-04-22

概要

先にテーブルを作っていて、後からmigrationで外部キー制約のついたカラムを追加(削除)したい時の書き方をまとめておきます。

Railsのバージョン(6.0.0)

前提条件

  • tweetsテーブルがあり、そこに外部キーであるuser_idカラムがある。
  • memosテーブルがある。
schema.rb
create_table "tweets", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t|
   t.string "content", null: false
   t.bigint "user_id", null: false
   t.datetime "created_at", precision: 6, null: false
   t.datetime "updated_at", precision: 6, null: false
   t.index ["user_id"], name: "index_tweets_on_user_id"
end

create_table "memos", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4", force: :cascade do |t|
   t.string "content", null: false
   t.bigint "tweet_id", null: false
   t.datetime "created_at", precision: 6, null: false
   t.datetime "updated_at", precision: 6, null: false
   t.index ["tweet_id"], name: "index_memos_on_tweet_id"
end

カラムを追加

tweetsテーブルに外部キー制約のmemo_idを追加する。

  1. マイグレーションファイルを生成する。
  2. 生成されたマイグレーションファイルを以下に書き換える。
(日付)_add_memo_id_to_tweets.rb
def change
  add_reference :tweets, :memo, null: false, foreign_key: true
end

カラム削除

tweetsテーブルから外部キー制約のuser_idを削除する。

  1. マイグレーションファイルを生成する。
  2. 生成されたマイグレーションファイルを以下に書き換える。
(日付)_remove_user_id_from_tweets.rb
def change
  remove_reference :tweets, :user, null: false, foreign_key: true
end

追記

indexはデフォルトでindex: trueになっているため、明示的に書かなくても良い。

1
1
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
1
1