1. Computing

Rails Blog Tutorial - Allowing Comments

By

4 of 7

Preparing the Comments Controller

The comments controller will not be used in the traditional way a RESTful controller is used. Firstly, it will be accessed solely from the Post views. The comment forms and display are entirely in the show action of the Post controller. So, to start with, delete the entire app/views/comments directory to delete all of the comment views. They won't be needed.

Next, you need to delete some of the actions from the Comments controller. All that's needed is the create and destroy actions. All other actions can be deleted. Since the Comments controller is now just a stub with no views, you have to change a few places in the controller where it attempts to redirect to the Comments controller. Wherever there is a redirect_to call, change it to redirect_to(@comment.post). Below is the complete comments controller.

# File: app/controllers/comments_controller.rb
class CommentsController < ApplicationController
  def create
    @comment = Comment.new(params[:comment])
 
    if @comment.save
      ;flash[:notice] = 'Comment was successfully created.'
      redirect_to(@comment.post)
    else
      flash[:notice] = "Error creating comment: #{@comment.errors}"
      redirect_to(@comment.post)
    end
  end
 
  def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy
 
    redirect_to(@comment.post)
  end
end
  1. About.com
  2. Computing
  3. Ruby
  4. Ruby on Rails
  5. Preparing the Comments Controller

©2014 About.com. All rights reserved.