8.1. Defining Routes with map.connect

When you create a new application, Rails generates a config\routes.rb file that defines two default (unnamed or anonymous) routes:

map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'

The routing subsystem will try to find a match between the defined patterns and the URL of the incoming request.

For example, take the first route into consideration:

map.connect ':controller/:action/:id'

This tells Rails that the route recognizes only paths that include an arbitrarily named controller, action, and id. Hence, '/library/borrow/25189' matches this route, and instructs Rails to map the first token in the URL (that is, library) to the :controller parameter, the second token (for example, borrow) to the :action parameter, and the third token to the :id parameter, which has a value of "25189." The params object will then look like this:

params = { :controller => "library", :action => "borrow", :id => "25189" }

Rails will therefore be able to process the request, by instantiating the library controller and executing the borrow action defined within it. As a developer, you'll be able to retrieve the :id parameter from within the controller through params[:id].

8.1.1. Default Parameters

/library/borrow/25189 results in the parameters { :controller => "library", :action=> "borrow", :id => "25189" }, but not all three parameters are strictly required.

You could omit an id, issuing perhaps a request for the path /library/catalog ...

Get Ruby on Rails® for Microsoft Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.