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

(Tuis.) #1

212 | Chapter 7: REST, Resources, and Web Services


You may occasionally see URIs like/people/1;editwhen reading
information about RESTful development in Rails. For a time, the semi-
colon was a route component separator (Rails 1.2 still uses it), but it
has since been removed in Rails 2.0.

These routes are also available in a_urlvariant that includes the scheme, host, and
port. For example,people_pathreturns/people, whilepeople_urlreturnshttp://
localhost:3000/people (of course, with the appropriate scheme, host, and port,
depending on that of the incoming request). In addition, there is ahash_for_variant
that returns a hash of parameters ready to be passed intourl_for, rather than return-
ing the URI directly as a string:


>> app.hash_for_people_path
=> {:action=>"index", :controller=>"people", :only_path=>true,
:use_route=>"people"}
>> app.hash_for_people_url
=> {:action=>"index", :controller=>"people", :only_path=>false,
:use_route=>"people"}

The app variable is an instance of ApplicationController::
Integration::Session(used for Rails integration testing) that is made
available at the Rails console. It can be used to troubleshoot control-
ler issues (such as routing), and even to make mock HTT Prequests of
the application, just as in integration testing:
$ script/console
Loading development environment.
>> app.get '/hello/world'
=> 200
>> app.response.headers
=> {"Status"=>"200 OK", "type"=>"text/html; charset=utf-8",
"cookie"=>[], "Cache-Control"=>"no-cache",
"Content-Length"=>13}
>> app.response.body
=> "Hello, world!"

Extra query string parameters can be added to the named routes, but in the case of
member routes, the member object or ID must be included in the hash as an:id
parameter:


$ script/console
Loading development environment.
>> app.person_path(1)
=> "/people/1"
>> app.person_path(:id => 1)

new_person_path /people/new {}
edit_person_path(1)
edit_person_path(@person)

/people/1/edit {:id => 1}

Named route URI Params
Free download pdf