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, ...
Get Learning Rails now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.