Restful routes

Hi, I'm pretty new to the concept of restful routing and am struggling
to find any rails 2 info that helps with what I'm looking for.

I have a regular scaffold setup and the routes are setup as default

map.resources :pages

I would like to be able to use titles in the url rather than relying on
the id.

instead of just


Can anyone help me out?


In your model you can override the to_param method like so

  def to_param
     "#{}-#{self.sometitle.downcase.gsub(/[^a-z0-9]+/i, '-')}"

and you'll get a route like

replacing sometitle with an attribute of your model.


oops... you really don't need to specify 'self' in there, just 'id'
and 'sometitle' will do.

Hi Dan,

I'm new to Rails myself, but I don't think you have a restful issue
here. I'll make a couple of assumptions:
You are calling the new page using a link_to helper and you are
calling the show action.

In your link_to, you probably see a restful named route called
something like pages_path(title). The sometitle is an instance
variable holding the ID field. You simply want to replace that with
title.sometitle. That will provide you the url you want.

But, that is only the first half. The receiving action, presumably
show, expects the ID, something like: Pages.find(params[:id]). You
will need to change that to Pages.find_by_title(params[:title]
[:sometitle], or something similar. This assumes title is a field in
the table pages.

Hope this helps.

Thanks guys, I'll save this thread and refer to it again. I find a lot
of things in Rails seem to take me a lot longer to understand than they

It's great that you're already trying to adhere to RESTful principles,
though! Many newcomers to Rails don't start that way and end up
feeling the pain later.


REST with Rails
Oct 4, 2008, in Austin, TX
$295 (get 10% off with discount code "PWRRGG")

rsl's stringex library also does the same thing: