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
MethodPathActionHelper
GET/productsindexproducts_url
GET/products/newnewnew_product_url
POST/productscreateproducts_ur
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:

Simple

Allows resource to be accessed RESTfully:

map.resources :products, :users

Nested

Allows resources to be accessed RESTfully within a container controller:

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

Customized

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.