Sha256: aaa76a2ea4599983d40e3dfea3607116ff117e6fae45f5af3b8b82f26e1d9dc3
Contents?: true
Size: 1.99 KB
Versions: 11
Compression:
Stored size: 1.99 KB
Contents
## Deleting Comments Another important feature on 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 `DELETE` action in the `CommentsController`. So first, let’s add the delete link in the `app/views/comments/_comment.html.erb` partial: @@@ html <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> @@@ Clicking this new “Destroy Comment” link will fire off a `DELETE /posts/:id/comments/:id` to our `CommentsController`, which can then use this to find the comment we want to delete, so let’s add a `destroy` action to our controller: @@@ ruby class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(params[:comment]) redirect_to post_path(@post) end def destroy @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) @comment.destroy redirect_to post_path(@post) end end @@@ The `destroy` action will find the post we are looking at, locate the comment within the `@post.comments` collection, and then remove it from the database and send us back to the `show` action for the post. ### Deleting Associated Objects If you delete a post then 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 `Post` model, `app/models/post.rb`, as follows: @@@ ruby class Post < ActiveRecord::Base validates :name, :presence => true validates :title, :presence => true, :length => { :minimum => 5 } has_many :comments, :dependent => :destroy end @@@
Version data entries
11 entries across 11 versions & 1 rubygems