0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】外部キー制約のon_delete: :restrict、:nullify、:cascadeの違い

Last updated at Posted at 2025-09-26

on_delete

Railsでデータベースの外部キー制約を設定する際、on_deleteで親レコードが削除されたときの動作を制御できます。

オプション

on_deleteには:restrict:nullify:cascadeを指定できます。

:restrict

親レコードの削除を阻止

add_foreign_key "revisions", "users", column: "created_by_id", on_delete: :restrict

userに関連するrevisionsが存在する場合、そのuserの削除はエラーとなります。

:nullify

関連する外部キーをnullに設定

add_foreign_key "revisions", "users", column: "created_by_id", on_delete: :nullify

userが削除されると、関連するrevisionscreated_by_idnullになります。

:cascade

関連レコードも連鎖削除

add_foreign_key "revisions", "users", column: "created_by_id", on_delete: :cascade

userが削除されると、関連するrevisionsも自動的に削除されます。

まとめ

オプション 動作
:restrict 削除を阻止
:nullify 外部キーをnullに
:cascade 関連レコードも削除
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?