Wednesday, March 9, 2011

Ruby on Rails RESTful routing

The following is for Rails 2.3.8 using Ruby 1.8.7

It is for Rails scaffold, but it more or less describes how things are done in Rails.

First, there is nothing yet.

For the Create in CRUD:

We need a form to create a record (unless somebody directly use a program to send an HTTP request to our server). The form is generated by:

the above generates a form in HTML.  It is a   GET /foos/new

nothing special there.

Note that for this form, when a user enters all the details, and click the "Create" button, it POST to /foos/ that is, it POST to

the Rails's FoosController#create action will handle it.

the HTTP request is:


Near the end of this create action, it redirects to

This is a GET /foos/1

and it is for the Retrieval in CRUD.

It is handled by FoosController#show action


For the Update in CRUD:

To edit something, we need a form, (unless using a program to directly submit the changes)

it is just a GEThandled by FoosController#edit action

when user clicks Update button, it sends


The Rails development log says it is a PUT, but Fiddler on Windows shows that it is a POST

the POST variables are


it is handled by FoosController#update action.

After the update, it redirects back to

to show you the record again.

Now the Destroy in CRUD:

The Destroy link is in /foos  which shows all the records for foo

Click on Destroy, and it does a   POST HTTP/1.1
with POST variables


so it is not a DELETE. It is handled by FoosController#destroy

To summarize:

Which of CRUDto prepare the formcontroller and action to prepare the formwhen the real action of CRUD is happeningcontroller and action
CGET /foos/newFoosController#newPOST /foos/FoosController#create
RGET /foos/1FoosController#show
UGET /foos/editFoosController#editPOST /foos/1     _method=putFoosController#update
DGET /foos/FoosController#indexPOST /foos/1     _method=deleteFoosController#destroy

This is tested again using Ruby 1.9.2 and Rails 3.0.5, and the Update and Delete are done the same way: using a POST, with _method=put or _method=delete.