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

Rails Blog Tutorial - Allowing Comments

By

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])
  <b>@comment = Comment.new( :post => @post )</b>

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 %>

  <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 %>
  1. About.com
  2. Technology
  3. Ruby
  4. Ruby on Rails
  5. The Comments Form

©2014 About.com. All rights reserved.