1. Computing

Using Yahoo! UI to Give Your Blog That "Blog Look"

By

7 of 10

Displaying Content Properly

Up until now, the blog content has just been displayed in a table generated by the scaffold generator which is not a desirable look. To be able to display blog posts correctly--title at top, followed by body--a partial will be created. Partials are a way to make your code follow the DRY (Don't Repeat Yourself) principle.

Since it's very likely you'll want to display blog posts in more than one action (such as index and show), you shouldn't write the code to display the blog post more than once. Create a new file in app/views/posts/ called _post.html.erb. The underscore at the beginning of the filename tells Rails this is not a view for an action, but rather a partial that will be "called" from another view.

The following code is what's placed inside of _post.html.erb. It's pretty standard: it places the entire blog post in a div, displays the title as a header tag (as a link) and formats the body using the simple_format helper. This will do things like create paragraph tags.

Also displayed are the various links to actions such as destroy and edit. You'll also notice that there is a local variable called post in the partial. This is assigned to when the partial is called from the view, either with the :collection, :object or :locals argument.

# File: _post.html.erb
<div class="post">
<h2><%= link_to post.title, post %></h2>
<%=simple_format post.body %>
<%= link_to 'Edit', edit_post_path(post) %>
<%= link_to 'Destroy', post,
:confirm => 'Are you sure?',
:method => :delete %>
<div>
  1. About.com
  2. Computing
  3. Ruby
  4. Ruby on Rails
  5. Displaying Content Properly

©2014 About.com. All rights reserved.