Rails Named Routes

I have already gone in some detail about creating custom routes for your Ruby on Rails application. At this time, I would like to recall that you can pass additional parameters to your controller by adding them in your routes.

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

The route above will resolve for a url such as the following.

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

For the above url, the controller can access two parameters, params[:id] and params[:xid]. Before nested routes where available in Rails, I would fake nested routes by creating routes like the following.

[source:ruby]
map.connect ‘:controller/:action/:id/comment/:xid’
[/source]

The route above would resolve for a url such as the one below if you had an action post in a controller blog.

http://mydomain.com/blog/post/1/comment/2

Because I was able to fake nested routes for my urls I really don’t understand why there is the need behind them.

Now, with the above background lets create a named route to view a blog post without naming both the controller and action.

[source:ruby]
map.post ‘post/:id’, :controller => ‘post’, :action => ‘show’
[/source]

The name of the route is post, named for the function call map.post. The route will resolve the following url to an action show in the post controller.

http://mydomain.com/post/1

Rails will create a post_url method which can be used in your rhtml view. In the rhtml view you can create the url for this route with the following snippet.

[source:ruby]
<%= post_url :id => @link.id %>
[/source]

In Rails 1.2 this will return an url as you expect.

http://mydomain.com/post/1

In Rails 1.6.1 this would return an string url with the controller and action name in it. If you are using Rails 1.6.1 and want your named route to resolve to the above url, use a different name for :id, such as :xid, in the routes definition.

If you are using Rails 1.2, you don’t have to pass in a hash parameter to the post_url view method. In Rails 1.2, you can pass in your ActiveRecord model for which the post_url method will use the models id in the generated url.

[source:ruby]
<%= post_url @link %>
[/source]

Technorati Tags: , , , , , ,