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:

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

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.

[source:ruby]
id = params[:id]
xid = params[:xid]
[/source]

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:

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

Technorati Tags: , , , ,