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

(Tuis.) #1
RESTful Rails | 211

Resource-Based Named Routes


Resource routing encapsulates all of the Rails CRUD actions into one routing
statement:


map.resources :cases

Theresourcesmethod sets up a series of RESTful named routes. Just with that one
statement, you can now uselink_to('View All', cases_path),link_to('Destroy',
case_path(@case), :method => :delete), and many more. This is more maintainable
because there are fewer named routes and they are standardized. It also encourages
you to model according to CRUD; you have to think carefully before adding ad-hoc
methods to controllers because each special case must be listed separately in the
route.


The following table shows the seven standard Rails CRUD actions, their semantics,
and the HTT Pphrases that they correspond to. It assumes a routing declaration of
map.resources :people.


The controller name defaults to the resource name; in this case, the routing code
would look for aPeopleController. This can be changed; specifyingmap.resources
:people, :controller => 'members' would instead look for aMembersController.


By default, Rails generates four basic named routes for themap.resources :people
declaration. The four routes are shown below, along with their corresponding URIs
and the parameters that are passed back to the controller in theparamshash when
the route is recognized.


Note that the URI generators will accept either an ID or an arbitrary object. Such
objects will be converted to a URI-friendly ID using#to_param, so anything that
responds to#to_param (such as anActiveRecord::Baseor ActiveResource::Base
object) will work.


HTTP Rails Semantics
GET /people index Shows a list of all people
GET /people/new new Shows a form to create a new person
POST /people create Creates a new person; redirects to its URI
GET /people/1 show Shows a representation of the specified person
GET /people/1/edit edit Shows an edit form for the specified person
PUT /people/1 update Updates the specified person with the provided data
DELETE /people/1 destroy Removes the specified person

Named route URI Params
people_path /people {}
person_path(1)
person_path(@person)

/people/1 {:id => 1}
Free download pdf