1. Computing

Rails Blog Tutorial - Allowing Comments

By

6 of 7

Displaying the Comments

The final step is to actually display the comments. Care must be taken when displaying user input data as a user might try to insert HTML tags which could disrupt the page. To prevent this, the h method is used. This method will escape any HTML tags the user tries to input. In a further iteration, a markup language such as RedCloth or a filtering method could be applied to allow users to post certain HTML tags.

Comments will be displayed with a partial, just as posts were. Create a file called app/views/posts/_comment.html.erb and place the following text in it. It will display the comment and, if the user is logged in and can delete the comment, also display the Destroy link to destroy the comment.

<div class="comment">
  <i><%=h comment.name %> says:</i><br />
  <%= simple_format h(comment.body) %>
  <%= link_to 'Destroy Comment', comment,
    :confirm => 'Are you sure?',
    :method => :delete if logged_in? %>
</div>

Finally, to display all of a post's comments at once, call the comments partial with :collection => @post.comments. This will call the comments partial for every comment that belongs to the post. Add the following line to the show view in the posts controller.

<%= render :partial => 'comment', :collection => @post.comments %>

One this is done, a fully-functional comment system is implemented.

  1. About.com
  2. Computing
  3. Ruby
  4. Ruby on Rails
  5. Displaying the Comments

©2014 About.com. All rights reserved.