Using Names in Rails Routes Instead of IDs

I spent tonight cranking through some Ruby on Rails has_many :through association oddities and after pounding my head against the keyboard, I decided to shift gears and figure out Ruby On Rails Routes.

By default, the Rails expects ID to be passed in URL strings. But that’s really lame, and passing words is much cooler so, how do you do that?

Turns out, it’s so simple no one talks about it (vs. so hard no one’s figured it out).

Take the following example:
http://mydomain/friend/show/1

What’s ‘show’? Who’s friend 1? Don’t they have a name?
Sure they do. Let’s say their name is ‘Wooster’

Here’s how to make turn the above url string into:
http://mydomain/friend/wooster

  1. Get the name of the database column storing your friends’ names (let’s say it’s ‘name’).
  2. In config/routes.rb add, somewhere above the default route:
    map.connect 'friend/:name', :controller => 'friends', :action => 'show'
  3. Now, in friends_controller, find def show and change it to:
    @friend = Friend.find_by_name(params[:name])
  4. Lastly, all the id-based urls pointing to our good friend Wooster need to be updated to reflect the name-based change. Like the one your Friends list.rhtml file.
    'show', :name => friend.name

5 thoughts on “Using Names in Rails Routes Instead of IDs

  1. io

    @misiek that’s pretty easy too… if you go to the command line and type “rake routes” you can see the paths it generates.
    the :id is there so then go to your associated controller and see how it’s used. it’s probably something like Friend.find(params[:id])
    Ruby doesn’t care about the type of that id could be an int or could be a string.
    just retype the line to Friend.find(:name=params[:id]) and (plus or minus SQL injection ) all should be fine.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>