Friday, October 19, 2007

Named Routes

The RoR project contains a file called routes.rb.

This file handles the routing of URIs to controller actions. Simple things can be done like routing www.mypage.com to some home page, or even a login page such as www.mypage.com/login by doing:

map.connect '', :controller => 'user', :action => 'login'

Something cool here can be done:

map.login 'login', :controller => 'user', :action => 'login'

gives us a shortcut to the login page. In our controller or in our view, we can now use:

login_url # www.mypage.com/login
login_path #/login


This is pretty neat as we can change all our paths to variable paths, and so if we decide to change the structure of our URIs, we only need to change them in one place!

Slightly more advanced are things called Named Routes. By specifying:

map.resources :user

we get several shortcuts that can be used in conjunction with HTTP methods (GET, POST, PUT, UPDATE). For example, we know have access to:

edit_user_path(@user.id)

which will give us the path /user/:id;edit. This will automatically call the edit action in our user controller. Pretty cool huh?

For more in depth information, try this website:

http://ryandaigle.com/articles/2006/08/01/whats-new-in-edge-rails-simply-restful-support-and-how-to-use-it

Named Routes naturally give way to RESTful development. If you don't know what that is, I recommend reading up on it. I'll talk about it sometime later, so check back!

W

No comments: