For example, we
may have this declaration in config/routes.rb:
map.resources :people, :collection => { :search => :get },
:member => { :deactivate => :post }
This sets up search_people_path and deactivate_person_path routes that have restrictions
so as only to accept the specified HTTPmethods. 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"]}
214 | Chapter 7: REST, Resources, and Web Services
The named routes will only be recognized given the proper HTTPmethod; if called
with other methods, they will return 404:
>> app.deactivate_person_path(1)
=> "/people/1/deactivate"
>> app.post app.deactivate_person_path(1)
=> 200
>> app.get app.deactivate_person_path(1)
=> 404
Note that defining custom routes like this can easily deviate from REST. It is easy to
overload a resource with many custom methods that may better be factored into
resources of their own. For example, rather than POSTing to /people/1/deactivate,
the RESTful action would be either to PUT active=0 to /people/1 or to PUT a value of
0 to /people/1/active, depending on whether active was modeled as a separate
resource or an attribute of the person resource.
Pages:
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336