LoginSignup
3
3

More than 3 years have passed since last update.

削除がうまくいかずエラーが出る。。。 ❏Rails❏

Last updated at Posted at 2019-12-03

ツイートを削除しようとしたら、こんなエラーが出た。

ActiveRecord::StatementInvalid in TweetsController#destroy

Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails

ダウンロード (6).png

僕はただツイートを削除したいだけなのに。。。


なぜエラーがでたのか

【結論】

tweetsテーブルcommentsテーブルで外部キー制約を結んでいたため。



【commentsテーブル】
21b53daebb42568420a0e4d42c965cf9.png

外部キーとして、tweet_idがあるのがわかります。

コメントは必ず何かしらのツイートに結びつきます。
勝手にツイートを削除すると、迷子のコメントが現れます!
これがエラーの正体です。


解決策

dependent: :destroyを追記。
ツイートを削除すると同時に、そのツイートに結びついたコメントも削除します。

app/models/tweet.rb
class Tweet < ApplicationRecord
  has_many :comments, dependent: :destroy
end



参考

https://qiita.com/kemako/items/e98174b9747e0b2c75a6



ではまた!

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