0
1

More than 3 years have passed since last update.

Formオブジェクトで作成したデータを削除する

Posted at

はじめに

掲示板を作成中Formオブジェクトを用いて投稿にタグ付け機能を実装する所まで行いました。
その後投稿詳細機能と問題の投稿削除機能を実装しましたが実際に投稿を削除してみたところ

Mysql2::Error: Cannot delete or update a parent row: a foreign key constraint fails (`アプリ名_development`.`poat_tag_relations`, CONSTRAINT `fk_rails_ca2d4f0737` FOREIGN KEY (`post_id`) REFERENCES `posts` (`id`))

というエラーが出てしまい削除ができませんでした。

調べたこと

エラー内容をよく読んでみると、投稿idは中間テーブルの外部キー(foreign key)に含まれて
デリートやアップデートができないよ!と書かれているのがわかります

外部キーの設定変更

今回はdestoryで外部キーとして設定している項目を削除させるように、dependent: :destroyを設定しようと思います
この簡単な設定により不具合なく投稿の削除ができるようになります

/app/models/post.rb
class Post < ApplicationRecord
  has_many   :post_tag_relations,foreign_key: :post_id, dependent: :destroy
  has_many   :tags, through: :post_tag_relations
  has_many   :comment
  belongs_to :user
end
0
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
0
1