Regarding the delete function of the review model in Rails, it originally worked without problems, but an error occurred after implementing the comment model. I have clarified the cause, so I will share it.
Ruby 2.6.5 Rails 6.0.3.3
Routing is nested with reveiw as the parent and comment as the child.
config/routes.rb
resources :reviews do
resources :comments, only: [:create, :destroy]
end
It was implemented so that the review would be deleted. Before the comment was implemented, it could be deleted as it is.
views/reviews/show.html.erb
<%= link_to review_path(id: @review.id), method: :delete do %>
<div>Delete review</div>
<div>You can delete the review here.</div>
<% end %>
Since we implemented comment as a child element of review, we must implement it so that comment is deleted at the same time as review is deleted. Therefore, modify models / review.rb as follows.
models/review.rb
has_many :comments
↓↓↓
models/review.rb
has_many :comments, dependent: :destroy
The deletion function implementation is completed here.
https://qiita.com/Tsh-43879562/items/fbc968453a7063776637
Recommended Posts