はじめに
データ削除時にConstraintException: FOREIGN KEY constraint failedというエラーがでたのでその解決方を書く。
モデル
Noteモデルが複数のカテゴリーをもつ。
この時Noteコントローラーで@note.destroyと書いたところ、次の様なエラーが発生した。

原因
このエラーの原因はNote_category_relationモデルに、
note_idを外部キーとして持っているためである。
つまり、Noteを削除する際、note_idを外部キーにもつNote_category_relationのデータも一緒に削除しなければいけないと言うこと。
エラー処理
これは編集前のNoteモデル。
app/models/note.rb
class Note < ApplicationRecord
has_many :note_category_relations #ここが問題
has_many :categories, through: :note_category_relations
end
このファイルを次の様に編集する。
app/models/note.rb
class Note < ApplicationRecord
has_many :note_category_relations, dependent: :destroy #追加部分
has_many :categories, through: :note_category_relations
end
has_many :note_category_relations, dependent: :destroyとすることによって、Noteが削除された時に、そのNoteを外部キーとして持っているnote_category_relationsも削除できる。
これでエラー解決です。
