The routes we have discussed so far are known as simple routes. I have been referring to them as custom routes, but ‘simple routes’ is the correct term. The default route we discussed in part 3 is also a simple route. The aim is to move onto RESTful routes, sometimes called resource routes. RESTful routes are built on top of named routes. Therefore we must first cover named routes, and that is what part 4 is all about.
Part 4
Introduction
Referring back to part 1, the routing system has two main functions:
Interpreting a request URL
Generating a request URL
We had a detailed look at route generation and interpretation in part 2, but let’s have another quick look at it. Let’s assume, for some insane reason, that we defined the following route in the music_store routes.rb file:
map.connect ‘apples/bananas/:id’, :controller => “albums”, :action => “show”
link_to would use this rule to generate a URL, this can be seen in the following line extracted from index.html.erb:
link_to ‘Show’, :controller => “albums”, :action => “show”, :id => album.id
This could generate a URL of: http://localhost:3000/apples/bananas/7
And when given this request, Rails would handle it correctly e.g. the show action will be called on the albums controller and the show view will be sent as the response to the browser.
Coming back to the real world, we are more likely to define the routing rule like this:
map.connect ‘albums/show/:id’, :controller => “albums”, :action => “show”
link_to (and friends) would then generate a URL like this:
http://localhost:3000/albums/show/7.
To show the index (the listing of the albums) we could define a rule like this:
map.connect ‘albums/index’, :controller => “albums”, :action => “index”
The matching link_to in edit.html.erb is:
link_to ‘Back’, :controller => “albums”, :action => “index”
Looking at the last example, there is some repetition. Both lines contain:
:controller => “albums”, :action => “index”
The link_to method needs this (controller, action) information to obtain the URL. If we had the URL stored as some global variable, or method, then we could simply pass that into link_to. link_to could use this ‘literal’ URL without needing to generate one.
This could look something like: link_to ‘Back’, albums_index_url
This is one of the main ideas behind named routes.
Posted by darynholmes
Posted by darynholmes
Posted by darynholmes 