Rails Action Controller - 4.3 Clarifying Your Code with Named Routes
(Page 4 of 4 )
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
Please check back next week for the continuation of this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter four of the Rails Cookbook. written by Rob Orsini (O'Reilly, 2007; ISBN: 0596527314). Check it out today at your favorite bookstore. Buy this book now.
|
|