In this fourth part of a series on the Action Pack library for Rails focusing on the view and the controller, we'll start writing some real code for an Action Pack controller. This article is excerpted from chapter six of the book Beginning Rails: From Novice to Professional, written by Jeffery Allan Hardy, Cloves Carneiro Jr. and Hampton Catlin (Apress; ISBN: 1590596862).
Writing an Action Pack Controller - Named Routes (Page 2 of 2 )
One of the coolest things about routing in Rails is a feature known as named routes. You can assign a name to a given route to make referring to it in code easier. Instead of defining a route withmap.connect, you replace theconnectpart with the name you want to give to the route.
For example, let’s take thealbums route we defined in the previous section and turn it into a named route.
With this definition in place, Rails will create methods that allow us to reference this particular route using its name:albums_urlandalbums_path. The*_urlvariant returns a full URL including the protocol and hostname (http://example.com/albums/list), whereas the*_pathvariant returns just the path (/albums/list).
We’ll cover redirection methods and hyperlink generation helpers later in this chapter, but we’ll point out now that you can use them with named routes:
As you can see, the result is identical. However, the named route is shorter, DRYer, and impervious to changes made at the routing level. So, if you were to change the controller name fromalbumstorecords, you wouldn’t need to update your links that use the named route; for the unnamed version, you would.
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.