LoginSignup
0
0

More than 3 years have passed since last update.

外部キーを持つデータの削除方法

Posted at

環境

この記事ではmacOS Catalina10.15.6にインストールしたRuby 2.6.5を使っています。

前提

3つのモデルを作成し、以下の状況となっています。

User / ユーザー
Report / レポート
Comment / ユーザーとレポートの関連付けテーブル

コメントがついているレポートの削除を行う際に、以下のエラーが発生しました。

エラー発生

ActiveRecord::InvalidForeignKey in ReportsController#destroy
外部キーエラー
スクリーンショット 2020-10-22 10.00.46.png

何が原因なのか、その解決策を考えます。

原因

レポートの削除を行う際に、コメントテーブルのユーザーとレポートのidの値がなくなることが原因と判断。(外部キー制約のため)
ユーザーとレポートのidの関連付けがなくなったものは、コメントも削除できるようにしたい。

解決策

dependent: :destroyUserモデルReportモデルに記述する。
この記述により、親モデル(Report)を削除する際に、その親モデルに紐づく「子モデル(Comment)」も一緒に削除できる」ようになります。

検証

app/models/user.rb
class User < ApplicationRecord
  has_many :reports
  has_many :comments, dependent: :destroy
end
app/models/report.rb
class Report < ApplicationRecord
  belongs_to :user
  has_many :comments, dependent: :destroy
end

無事解決しました!
以上です。
同じような悩みや壁にぶつかっている方のお役に立てれば幸いです!

参考

下記を参考にしたので、より深く内容を理解したい方は、見てみてください!
https://qiita.com/Ushinji/items/650fa295a3054d2fe582
https://qiita.com/ITmanbow/items/2170ccaceafd5d401df8
https://qiita.com/Tsh-43879562/items/fbc968453a7063776637

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