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:

www.mysite.com/foos/new

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 www.mysite.com/foos/

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

the HTTP request is:

POST http://www.mysite.com/foos/ HTTP/1.1

Near the end of this create action, it redirects to http://www.mysite.com/foos/1

This is a GET /foos/1

and it is for the Retrieval in CRUD.

It is handled by FoosController#show action

GET http://www.mysite.com/foos/1 HTTP/1.1

For the Update in CRUD:

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


  http://www.mysite.com/foos/1/edit

it is just a GEThandled by FoosController#edit action

when user clicks Update button, it sends


POST http://www.mysite.com/foos/1 HTTP/1.1

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

the POST variables are

_method=put&authenticity_token=9dMLgD4E6liD2%2Bo7dOVsBJ7B3Vdy9e2v%2F5bE36YgpYE%3D&foo%5Bs%5D=hi&foo%5Bi%5D=333&foo%5Bf%5D=2.0&foo%5Bnote%5D=wah&commit=Update

it is handled by FoosController#update action.

After the update, it redirects back to

http://www.mysite.com/foos/1

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://www.mysite.com/foos/1 HTTP/1.1
with POST variables

_method=delete&authenticity_token=9dMLgD4E6liD2%2Bo7dOVsBJ7B3Vdy9e2v%2F5bE36YgpYE%3D

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.


Followers