Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
RESTful Rails | 213

=> "/people/1"
>> app.person_path(:id => 1, :section => 'enrollment')
=> "/people/1?section=enrollment"

Similarly, the default collection routes can also take a hash of query string
parameters:


>> app.people_path(:sort => 'last_name')
=> "/people?sort=last_name"

Routes can also be generated with a specific format; any of the formats specified in
Mime::Types(discussed later) are valid. There is another series offormatted_named
routes for this purpose:


>> app.formatted_person_path(1, :js)
=> "/people/1.js"
>> app.formatted_person_path(1, :xml)
=> "/people/1.xml"
>> app.formatted_people_path(:rss)
=> "/people.rss"

This is useful in conjunction withrespond_to, which switches responses based on the
content type accepted by the client. Note that, like the other named routes, if we want
custom query string parameters, we must convert all of the arguments to a hash:


>> app.formatted_person_path(:id => 1, :format => :xml,
:section => 'enrollment')
=> "/people/1.xml?section=enrollment"

Custom resource routes


The REST helpers also have provisions to create custom named routes pertaining
either to the collection (the parent resource) or the members of the collection (the chil-
dren). These are created with the:collectionand:memberoptions tomap.resources,
respectively. Each new route must have a corresponding HTT Pverb it is to be used
with. The routes directly correspond to actions on the controller. For example, we
may have this declaration inconfig/routes.rb:


map.resources :people, :collection => { :search => :get },
:member => { :deactivate => :post }

This sets upsearch_people_pathanddeactivate_person_pathroutes that have restric-
tions so as only to accept the specified HTT Pmethods. We can try these out at the
console:


$ script/console
Loading development environment.
>> app.search_people_path(:query => 'Brian')
=> "/people/search?query=Brian"
>> app.get app.search_people_path(:query => 'Brian')
=> 200
>> app.request.request_uri
=> "/people/search?query=Brian"
>> app.request.params
=> {"query"=>["Brian"]}
Free download pdf