Creating Custom Rails Routes

There comes a time in a Ruby on Rails project that will require a custom routes definition. Routes, in rails, are somewhat similar to what you can do in Apache’s .htaccess files, that is you can map URLs to different locations. For example, if you use WordPress you will need to edit your .htaccess file so that you can create permalinks. In Rails, you can create routes so that a given URL is managed by the right controller. Here is a routes example. Lets say that I want to write a ‘are you hot or not’ type of application and I need to find two records at the same time from the database. In this case the records are pictures of hot chicks. To do this I would first start by editing the rails config/routes.rb file and add the following routing:

# Sometimes I need an extra id
map.connect ‘:controller/:action/:id/:xid’

This route will resolve any url that looks like this:

http://mydomain.com/myrailsapp/mycontroller/myaction/1/2

Where 1 and 2 are the record ids. In the controller you have access to these ids via the params variable.

id = params[:id]
xid = params[:xid]

Another example of when to use routes could be when you want the url to remain the same but need the flexibility to refactor or rename the controller at a later point. In this case you can use a routing that is similar to the following:

map.connect ‘user/:id’, :controller => ‘admin/user’, :action => ‘profile’

Technorati Tags: , , , ,

Enjoy. Share. Be Happy.
  • Twitter
  • Facebook
  • StumbleUpon
  • del.icio.us
  • Tumblr
  • Google Bookmarks
  • FriendFeed
  • Yahoo! Buzz
  • Reddit
  • Digg
  • HackerNews
  • Suggest to Techmeme via Twitter
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • Mixx
  • Furl

Related posts:

  1. Rails Named Routes
  2. Ruby On Rails Controller Path
  3. Rails Google Maps Plugin
  4. Creating Internet Shortcuts in Windows
  5. Rails Acts As Authenticated Plugin

This entry was posted in Ruby, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Trackback

  1. By Mike Schinkel's Miscellaneous Ramblings on February 19, 2007 at 11:55 pm

    On the Hunt for a New Programming Language…

    On the Hunt for a New Programming Language, I detail my current impressions of a…

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*