rails4 8 Deleting Comments

删除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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值