1
1

More than 3 years have passed since last update.

[Rails]外部キー制限かかっているときにdestoryできないエラーを発生させたい時の対処

Last updated at Posted at 2020-09-12

はじめに

レコード削除時に関連づけられたレコードが存在するときに、例外やエラーを発生させたい。
外部キーで使用されていると親要素が消されては困るというシチュエーションです。

削除しようとするとRubyのエラー画面が出てしまう。

原因

Modelに関係づけされたモデルに対する挙動を定義するが無いからでした。
マイグレーションファイルのforeign key: Trueだけでは不十分でした。

対策

Modeldependentオプションを記述することで解決しました。
該当のモデルに以下の記述をします。

#contractというモデル
class Contract < ApplicationRecord
  has_many :...., dependent: :restrict_with_error

end

アソシエーション記述の後にdependent: :restrict_with_errorと記述することでdestoryできないときのエラーを表示することができた。
以下の条件分が成り立ち解決しました!。


#contractというモデルのコントローラー
def destroy
    contract = Contract.find(params[:id])
    if contract.destroy
      redirect_to contract_path, notice: "選んだ契約を削除しました"
    else
      redirect_to contract_path, alert: "使用中のため削除できません"
    end
end

参照

https://dorarep.page/articles/rails-dependent#dependent_restrict_with_exception_restrict_with_error

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