A Routes.rb Primer

May 06, 2006

After you get past the learning curve, using custom routes in Rails gives you a vast amount of control over how your application displays and handles URLs. I like to use them for aesthetic reasons, and it helps satiate my obsession with pretty URLs.

For example, in this notebook if you’d like to see all the posts tagged with “rails” the URL would be this:

http://www.myersds.com/notebook/tags/rails

Nice and human readable, see? But behind the scenes what’s really going on is something closer to this:

http://www.myersds.com/notebook/tags/show_posts_with_tag?name=rails

While not confusing, it just isn’t as nice nor is it easy to remember.

How do we achieve this little gem of functionality?

Routes.rb

The magic happens in the routes.rb file in the config folder. The common default route you’ll see there is this:

map.connect ':controller/:action/:id'

This is what most people use when starting out with Rails, and is usually a dead giveaway that a web app is using the Rails framework when you see things such as “edit/post/3”. So here’s what my custom route looks like for tag searching:

map.connect 'notebook/tags/:name', 
    :controller => "notebook",
    :action => "show_posts_with_tag" 

So what does this do? First it matches any URLs matching the /notebook/tags pattern. It then takes whatever follows and stores it in the params hash under “name”. This is the tag we’re going to search on. It then routes the request to the notebook controller and calls the show_posts_with_tag method. We access our tag through params[:name]. The rest is just querying the database to get your results out and displaying them nicely on the page.

Generating URLs

The last part of routes pattern matching is generating the URLs for the tag links. How do we set the link of the “rails” tag to generate this?

http://www.myersds.com/notebook/tags/rails

It’s fairly easy, since the routes.rb is used for pattern matching in both incoming URLs and generating URLs, you just use the link_to tag normally:

<%= link_to(
   tag.name,
   :controller => "notebook",
   :action => "show_posts_with_tag",
   :name => tag.name
) %>

Our custom route will be matched correctly and we’ll have our nice well formatted URL.

Final Notes

This just scratches the surface of what you can do with Rails Routes, but it should give you a decent idea of how to write your own custom routes. You can find further documentation in this routes manual on the Ruby on Rails site, and there’s a good chapter devoted to it as well in the Agile Development with Rails book.