Rails3入门之九 删除评论

另外一个重要的功能是blog可以删除垃圾评论。为了完成这个功能,我们需要实现一个link和delete动作在CommentsController控制器里面。

 

所以首先,让我们添加DELETE链接在app/views/comments/_comment.html.erb 模板。

<p>
  <b>Commenter:</b>
  <%=comment.commenter %>
</p>
  
<p>
  <b>Comment:</b>
  <%=comment.body %>
</p>
  
<p>
  <%=link_to 'Destroy Comment', [comment.post, comment],
               :confirm=> 'Are you sure?',
               :method=> :delete %>
</p>

点击Destroy Comment”链接将会调用DELETE 动作,/posts/:id/comments/:id 传给我们

CommentsController。根据ID可以找到我们想删除的comment。所以我们

添加一个删除的方法在控制器中。

class CommentsController < ApplicationController
  
  defcreate
    @post= Post.find(params[:post_id])
    @comment= @post.comments.create(params[:comment])
    redirect_to post_path(@post)
  end
  
  defdestroy
    @post= Post.find(params[:post_id])
    @comment= @post.comments.find(params[:id])
    @comment.destroy
    redirect_to post_path(@post)
  end
  
end

 我们添加的destory方法将会发现要删除的评论,定位评论在@post.comments里面,

然后从数据库中删除,返回post显示页面。

 

9.1 删除有关系的对象

如果你删除一个博客那博客相关的评论也需要删除。否则将会浪费数据库空间,成为冗余数据。

rails允许我们利用dependent关键字来完成此功能。

修改app/models/post.rb像下面一样。

class Post < ActiveRecord::Base
  validates :name:presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
  has_many :comments, :dependent => :destroy
end

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值