删除comments
一个blog的另外一个重要的特征就是能够删除多余的comments。为了做到这个,我们需要在视图中实现一系列的代码,以及在CommentsController中实现destroy的action。
因此首先,让我们来增加删除的链接,在局部文件中 app/views/comments/_comment.html.erb:
<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> |
点击这个新的链接“Destroy Comment”将会发送一个 DELETE /articles/:article_id/comments/:id 到我们的CommentsController,用这个来找到我们想要删除的comment,因此让我们在我们的控制器中来增加一个destroy的action app/controllers/comments_controller.rb:
classCommentsController < ApplicationController defcreate @article= Article.find(params[:article_id]) @comment= @article.comments.create(comment_params) redirect_to article_path(@article) end
defdestroy @article= Article.find(params[:article_id]) @comment= @article.comments.find(params[:id]) @comment.destroy redirect_to article_path(@article) end
private defcomment_params params.require(:comment).permit(:commenter, :body) end end |
这个destroy的action将会找到我们正在寻找的article,在@article.comments的集合中定位到这个comment,然后从数据库中去删除它,最后我们在返回到显示article的界面上。
original text: http://guides.rubyonrails.org/getting_started.html#deleting-comments