LoginSignup
0
0

More than 1 year has passed since last update.

【初見】ActiveRecord::InvalidForeignKey を初学者なりに噛み砕いて備忘録を記述してみる。

Posted at

タイトルにもあるとおり始めてのエラーです(多分)

Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails とありまして、何が原因になっていたかを備忘録として書き残そうと思います。

解決策から紹介します。

このエラーの解決は、モデルに追記した後に、データベースをリセットすることで、解決しました。
コードだけだと意味がわからない記述になっているの以下の説明も一緒に読んでください。

# model/study_time.rb
belongs_to :skill, optional: true #optional: true を追記

# mdoel/skill.rb

has_many :study_time, foreign_key: :skill_id, dependent: :destroy #foreign_key: :skill_id, dependent: :destroy を追記

どういう仕組みで起こったのか。

作成しているアプリケーションを例に出しますと・・・・。
・ユーザーがスキルテーブルにAを作成します。
・アプリケーションには学習時間を追加する機能(スタディータイムテーブル)があり、ユーザーはスキルAに学習時間を追加していきます。(学習時間を追加するために、スキルをforeign_keyで制約を結んでいます。)
そこでスキルAを削除しようとすると、スタディーテーブルに、スキルAの学習時間が残ってしまっている状態になり、タイトルのエラーを吐きだすと、いうことになります。

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