This article uses Ruby 2.6.5 installed on macOS Catalina 10.15.6.
We have created three models and the situation is as follows.
User / User Report / Report Comment / User-report association table
The following error occurred when deleting a report with comments.
ActiveRecord::InvalidForeignKey in ReportsController#destroy Foreign key error
Think about the solution to what is the cause.
When deleting a report, it is determined that the cause is that the user in the comment table and the id value of the report are lost. (Due to foreign key constraints) I want to be able to delete comments if the user and report ids are no longer associated.
dependent: :Describe destroy in User model and Report model.
With this description, when you delete the parent model (Report), you can also delete the "child model (Comment)" associated with the parent model. " ## Verification #### **`app/models/user.rb`** ```ruby class User < ApplicationRecord has_many :reports has_many :comments, dependent: :destroy end
class Report < ApplicationRecord belongs_to :user has_many :comments, dependent: :destroy end
Completed without incident! that's all. I hope it helps those who have similar problems or are hitting a wall!
I referred to the following, so if you want to understand the contents more deeply, please take a look! https://qiita.com/Ushinji/items/650fa295a3054d2fe582 https://qiita.com/ITmanbow/items/2170ccaceafd5d401df8 https://qiita.com/Tsh-43879562/items/fbc968453a7063776637