Recipe 4.3. Clarifying Your Code with Named Routes


Problem

You are using link_to tHRoughout your application to generate URLs programmatically, but you still find that there's duplication across these calls for URLs that you use often. You want a shorthand way to refer to the most common routes in your application.

Solution

Use named routes.

Discussion

In your application's config/routes.rb file, you can create named routes simply by replacing map.connect with map. name, where name can be a descriptive name for that specific route definition.

Here's a named route, called admin_report, that routes a request to the report action of the Admin controller:

map.admin_report 'report/:year',                   :controller => 'admin',                   :action => 'report'

Having this named route in routes.rb tells Rails to create two new methods associated with this route: admin_report_url and hash_for_admin_report_url. You use the first method, admin_report_url, to reference this route anywhere that Rails requires a URL. The latter method just returns the routing hash for that route. With this named route defined, we can now use admin_report_url in a link_to helper:

<%= link_to "Administrative Report", admin_report_url(:year => 2005) %>

Internally, admin_report_url is a call to url_for that's passed the hash from the route definition. Any additional hash entries can be passed as arguments to admin_report_url; these entries are merged with the hash from the route definition, and are dealt with according to the rules defined by that route. In this example, the year for the report is passed as an argument to the admin_report_url method.

It's common to define a named route for the main page of your application. Here's how to define such a route called home that takes you to the page managed by the Main controller:

map.home '', :controller => "main" 

You can use this route in a redirect within a controller:

redirect_to home_url

See Also

  • Section 4.2"

  • Section 4.4"

  • Section 7.15"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net