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

Rails Blog Tutorial - Adding RESTful Authentication


7 of 8

Cleaning up the View

Authentication is now fully implemented but there are just a few small things to clean up before it's presentable. Firstly, the Sessions controller has no layout file. This means it's a blank white page that doesn't fit with the rest of the application. The fix for this is to rename the posts.html.erb layout file to application.html.erb, which will make it an application-wide layout file.

$ mv app/views/layouts/posts.html.erb app/views/layouts/application.html.erb # On Windows, use rename instead of mv

The final piece of clean-up required is to show administration links only if the user is logged in. Normal users shouldn't be able to see the Edit and Destroy links. Even though they can't access these actions without authentication, they don't really need to be able to see them either.

The logged_in? helper function can tell you if a user is logged in. The administration links are displayed in only two places. The partial used to display the post objects has the edit and delete links and the index action has the new post link. Changes to these files are highlighted in bold below.

# File: app/views/posts/_post.html.erb<br>  <div class="post"><br>    <h2><%= link_to post.title, post %></h2><br>    <%=simple_format post.body %><br>    <b><%- if logged_in? %></b><br>    <%= link_to 'Edit', edit_post_path(post) %><br>    <%= link_to 'Destroy', post,<br>      :confirm => 'Are you sure?',<br>      :method => :delete %><br>    <b><%- end %></b><br>  <div><br>
# File: app/views/posts/index.html.erb
 <%= render :partial => 'post', :collection => @posts %>
 <%= link_to 'New post', new_post_path if logged_in? %>
  1. About.com
  2. Technology
  3. Ruby
  4. Ruby on Rails
  5. Cleaning up the View

©2014 About.com. All rights reserved.