When I delete a post model record, I want to delete a comment model record associated with it, but I get the following error.
Currently, if there is no comment, it can be deleted normally.
If anyone understands, please take care of me.
The current code looks like this
The cord looks like it's going to work properly.
How do you delete the post model?
There are several ways to delete a record, but Rails generally uses one of the four ActiveRecord methods.
delete, delete_all, destroy, destroy_all.
There are four things that may be confusing, but in order to delete them so that they don't get the error,
You need to erase it like this.
There are four deep-fried methods, delete and destory.
The difference is
Defined in Post Model
This. This dependency definition is equivalent to a callback and will not be executed if deleted using the delete method.
Therefore, the following SQL will be issued as soon as the method is executed.
As the migration file in CreateComments defines the FK,
The records in the comments table are always configured to have the id of the records in the parent posts table.
If you delete the posts record with the comments left, the comments will float in orphaned state, so there is an FK error to prevent them.
To avoid this error, you must first erase the comments records, but to do so, you must use the destroy method as well as the definition of
© 2022 OneMinuteCode. All rights reserved.