1
1

More than 1 year has passed since last update.

#Rails マイグレーションで on_delete: :nullify を指定して、 DB に ON DELETE SET NULL の外部キー制約を追加する

Last updated at Posted at 2019-11-08

class CreateBook < ActiveRecord::Migration[5.2]
  def change
    create_table :book do |t|
      t.references :user, foreign_key: { on_delete: :nullify }
    end

    # あとから追加する場合は多分こう
    # add_foreign_key "books", "users", on_update: :nullify
  end
end

ON DELETE SET NULL とは

  • 親のレコード = user が削除された時に、子が持っている親のID = user_id が null に更新される
  • 親のレコード = user が削除された時に、子のレコード = book は削除されない

参考

外部キー制約について - Qiita

Original by Github issue

チャットメンバー募集

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

Twitter

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