Features I’m Currently Infatuated with in Rails

In Rails, Ruby on August 5, 2009 by Matt Grande

I’ve recently started a new project in Rails and I’m trying to follow all the best practices. Sometimes at my company they have fallen by the wayside, but I’m really putting an effort into enforcing them on the team. In doing so, I’ve started using a few methods that I’ve known about for awhile, but never really had a chance to use.

Nested Routes

In a blog, Post has_many Comments, that’s a given. Wouldn’t it be nice if your URLs reflected this relationship? Now they can! In your routes file, simply add map.resources :post, :has_many => [:comments]. Then, change your paths from new_comment_path to new_post_comment_path(@post). In your CommentsController, you’ll have access to both params[:id] and params[:post_id] now.

While we’re talking about related objects, rather than creating objects like this:

@post = Post.find(params[:post_id])
@comment =[:comment])
@comment.post_id =

Do something like this:

@post = Post.find(params[:post_id])
@comment =[:comment])

This way, your association is automatically built.

The new and improved render method

This has been in Rails for awhile now, but I’m just now getting a chance to use it. I always hated doing this:

<% @comments.each do |comment| %>
  <%= render :partial => "comments/comment", :locals => { :comment => comment } %>
<% end %>

It seemed so overly verbose, having the singular and plural form of ‘comment’ in there six times. As of Rails 2.2 (I believe) there’s been a handy helper, though.

<%= render @comments %>

The loops through all of your comments and renders them into the partial ‘comments/_comment.html.erb’ and give them a variable name of comment. But what do you do when you’re in the partial? Well that brings me to my next point…

The joy of div_for

You’re in a comment partial. You want to wrap the comment in a div with a unique id. You want to give all your comments the same class. Don’t do this:

<div id="comment_<%= -%>" class="comment">
  <!-- display the comment --></div>

when you can do this:

<% div_for(comment) do %>
  <!-- display the comment -->
<% end %>

Nice and easy.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: