1.14. REST

In Rails 2.1, one of the largest improvements made to the Rails framework was the addition of RESTful resources through ActionController::Resources. A RESTful resource is something that can be pointed at and will respond with a representation of the data requested. Instead of assigning the action to be taken within the parameters of the request or in the path, the method used along with the path determines what will happen.

For example, let’s take a product model and make it RESTful. To do this, we need to add the line into routes.rb:

map.resources :products

By adding this line into the routes configuration, the Product model is now a RESTful resource.

Our routes now might look something like Table 1-3.

Table 1-3. RESTful routes
GET/products/1/editeditedit_product_url(:id => 1)
PUT/products/1updateproducts_url(:id => 1)
GET/products/1showproduct_url(:id => 1)
DELETE/products/1destroyproduct_url(:id => 1)

As you can see, the combination of the request method used and the URL will determine the action.

1.14.1. RESTful Resources

There are three different ways to add resources to your routes:


Allows resource to be accessed RESTfully:

map.resources :products, :users


Allows resources to be accessed RESTfully within a container controller:

map.resources :admin do |admin|
  admin.resources :users


Resources that have customized options. Available options ...

Get Rails Pocket Reference now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.