1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Rails Blog Tutorial - Allowing Comments


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.'
      flash[:notice] = "Error creating comment: #{@comment.errors}"
  def destroy
    @comment = Comment.find(params[:id])
  1. About.com
  2. Technology
  3. Ruby
  4. Ruby on Rails
  5. Preparing the Comments Controller

©2014 About.com. All rights reserved.