Rails '5.2.3' Ruby '2.7.1' PostgreSQL
I tried to delete the registered item while checking the operation in the local environment while creating the review sharing application.
ActiveRecord::InvalidForeignKey in ItemsController#destroy
PG::ForeignKeyViolation: ERROR: update or delete on table "reviews" violates foreign key constraint "fk_rails_5350d1b47c" on table "comments" DETAIL: Key (id)=(6) is still referenced from table "comments". : DELETE FROM "reviews" WHERE "reviews"."id" = $1
Error ,. There is no comment table called ʻon table" comments "`. I was worried, but when I first created the app, I was thinking of creating a comment function for review, but isn't it necessary to have a one-sided comment function for review? There was a past that I stopped implementing it because I thought (I forgot). However, I thought that the comments table was deleted and I was addicted to it.
The relationship is that an item has multiple reviews while creating a review sharing app in Rails.
has_many :category_items, dependent: :destroy has_many :categories, through: :category_items has_many :reviews, dependent: :destroy has_many :favorites, dependent: :destroy accepts_nested_attributes_for :category_items
belongs_to :user belongs_to :item has_many :notifications, dependent: :destroy
From here, it is a consideration that a beginner thought. I would appreciate it if you could point out if it is different.
At the same time you try to delete the item, the review associated with the item will also be deleted.
has_many: reviews, dependent:: destroy This.
So this time, item is deleted → review disappears → comment table remains
(abridgement) has_many :comments, dependent: :destroy
I thought that it was a phenomenon that review could not be erased because there was no description, so item could not be erased.
First of all, it is a confirmation that the comments table really remains.
Updated db / schema.rb with
rails db: schema: dump.
Then look at schema.rb
create_table "comments", force: :cascade do |t| (abridgement) end
I had comments ... Delete unnecessary tables.
Create a migration file and write the following
def change drop_table :comments end
Goodbye with rails db: migrate. Now you can delete the review for both items! !!
I wrote it for a long time with just this, but the lesson I learned in this case is that machines will not betray, and it is the first person to doubt. The assumption is not good. It's my first post, so there are a lot of things I'm not sure about, but I hope it helps someone.