Another important feature of a blog is being able to delete spam comments. To do this, we need to implement a link of some sort in the view and a destroy action in the CommentsController.
So first, let's add the delete link in the app/views/comments/_comment.html.erb partial:
<p> <strong>Commenter:</strong><%= comment.commenter %></p><p><strong>Comment:</strong><%= comment.body %></p><p><%= link_to 'Destroy Comment', [comment.article, comment],method: :delete,data: { confirm: 'Are you sure?' } %></p>
Clicking this new "Destroy Comment" link will fire off a DELETE /articles/:article_id/comments/:idto ourCommentsController, which can then use this to find the comment we want to delete, so let's add a destroy action to our controller (app/controllers/comments_controller.rb):
class CommentsController < ApplicationControllerdef create@article = Article.find(params[:article_id])@comment = @article.comments.create(comment_params)redirect_to article_path(@article)enddef destroy@article = Article.find(params[:article_id])@comment = @article.comments.find(params[:id])@comment.destroyredirect_to article_path(@article)endprivatedef comment_paramsparams.require(:comment).permit(:commenter, :body)endend
The destroy action will find the article we are looking at, locate the comment within the @article.comments collection, and then remove it from the database and send us back to the show action for the article.
Deleting Associated Objects
If you delete an article, its associated comments will also need to be deleted, otherwise they would simply occupy space in the database. Rails allows you to use the dependent option of an association to achieve this. Modify the Article model, app/models/article.rb, as follows:
class Article < ApplicationRecordhas_many :comments, dependent: :destroyvalidates :title, presence: true,length: { minimum: 5 }end