Rails Action Controller - 4.3 Clarifying Your Code with Named Routes (Page 4 of 4 )
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.
Use named routes.
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:
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:
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:
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.