1. Home
  2. Computing & Technology
  3. Ruby

Rails Blog Tutorial - Allowing Comments

By , About.com Guide

5 of 7

The Comments Form

One of the final pieces to put into place is the comments form, which is actually a rather simple task. There are basically two things to do: create a new Comment object in the show action of the posts controller and display a form that submits to the create action of the Comments controller. To do so, modify the show action in the posts controller to look like the following. The added line is in bold.

# File: app/controllers/posts_controller.rb
# GET /posts/1
# GET /posts/1.xml
def show
  @post = Post.find(params[:id])
  @comment = Comment.new( :post => @post )

Displaying the comment form is the same as any other form. Place this at the bottom of the view for the show action in the posts controller.

<hr />
<% form_for @comment do|f| %>
  <%= f.error_messages %>
  <%= f.hidden_field :post_id %>
M
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>

  <p>
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </p>

  <p>
    <%= f.label :body %><br />
    <%= f.text_area :body %>
  </p>

  <p>
    <%= f.submit "Post Comment" %>
  </p>
<% end %>
Explore Ruby
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Ruby
  4. Ruby on Rails
  5. The Comments Form

©2009 About.com, a part of The New York Times Company.

All rights reserved.