另外一个重要的功能是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
=> :destroyend |
本文介绍如何在Rails应用中实现删除博客评论的功能,并通过设置依赖性确保删除博客时其关联评论也被一并清除。
701

被折叠的 条评论
为什么被折叠?



