O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generating URIs from Views and Controllers

Setting up these routes does more than connect URIs to your application. It also makes it easy for you to build connections between different parts of your application. Code can tell Rails what functionality it should point to, and Rails will generate an appropriate URI. There are many methods that generate URIs (form_for, link_to, and a host of others), but all of them rely on url_for, a helper method in the UrlModule class.

Pointing url_for in the Right Direction

The method signature for url_for doesn’t tell you very much about how to call it:

url_for(options = {})

Note

Remember, the parentheses around the method arguments are optional, as are the curly braces ({}) around the options hash.

Early Rails applications often called url_for by specifying all of the parts needed to create a URI—:controller, :action, and maybe :id:

url_for :action => 'bio', :controller => 'presidents', :id => '39'

This would produce a URI like:

/presidents/bio/39

There’s a simpler approach, though, if you just want to point to a particular object, say an @president object that has an id of 39:

url_for @president

Rails will check through its naming conventions, looking for a named route that matches the object specified. It will then call the named route’s _path helper method—in this case, probably president_path. The value returned by that helper will end up in the URI, likely as:

/presidents/39

To point to nested resources, you need to provide a little more information, two ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required