I'm creating SNS like Twitter and Fb. I added a delete button to the post function ... ** I can't delete the post! !! ** **
In more detail, you can delete just a post. Post a photo in the post (only if it is divided into post model and image model) If you comment on a post, you will not be able to delete it. ..
** [Today's characters] ** (Parent) post model → Model to save posts (Child) image model → Model to save the image associated with the post (Child) comment model → Model to save comments for posts
In other words, if a value is entered in the ** child model (image model, comment model) ** nested in the ** post model **, the post record cannot be deleted.
Let's take a look at the actual code.
post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments
has_many :images
end
It's an ordinary post model association. However, if this is left as it is, the parent model cannot be erased when a value is entered in the child model. Because if the parent disappears, ** the child's parent will disappear **. .. It's natural lol
In other words, when you delete a parent, you can set the child to be deleted as well **.
Let's set ** "dependent:: destroy" ** in the model. dependent ... Translated, it's "dependent". I think it's easy to get an image.
The model that was set at the time of this association will be deleted when the class is deleted. I don't know what you're saying, I'll actually write it below.
post.rb
class Post < ApplicationRecord
belongs_to :user
has_many :comments, dependent: :destroy
has_many :images, dependent: :destroy
end
Did you understand somehow? You have set the ** image model ** and ** comment model ** in the ** Post class **. When the post model (post) is deleted, the model (image, comment) for which ** dependent:: destroy ** is set in the association is also deleted.
There is something I would like you to be aware of regarding this. Actually, this ** dependent:: destroy ** is not a setting to delete the child model.
For example, let's write the following in the comment model.
comment.rb
belongs_to :post, dependent: :destroy
If this happens, if you delete the comment, ** the post will also be deleted **.
I will say it again. ** Models configured at the time of association will be deleted when the class is deleted. ** **
Thank you for reading my poor explanation to the end. If you have any mistakes or supplements, I would appreciate it if you could comment.
More and more.
Recommended Posts