Using Names in Rails Routes Instead of IDs

20 Jul 2006 in Programming, Ruby on Rails by Garrick

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

Comment | Trackback URL Short Link:

Add a Comment


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

Related Entries




Creative Commons License
About Sitemap XHTML Sitemap XML
Wordpress theme is a heavily hacked version of "Modicus Remix" by Art Culture. Original by Upstart Blogger