Restful Rails

Posted by admin, Thu Jun 21 10:30:00 UTC 2007

I recently took the decision to move to using restful rails. In simple terms it removes the action from the URL and uses HTTP's built-in functionality to determine the actions being requested.

So, instead of requesting /users/show/1 you simply request /users/1 with a (normal) HTTP GET method.

No shocks there - pretty sensible and obvious.

To update a user you perform a HTTP PUT method on the same URL, and to delete you perfrom HTTP DELETE.

There are some niggles - such as coping with edits and news but rails identifies these by appending the action after the URL with a semi-colon delimiter - /users/1;edit or /users;new.

To turn on restful routes you simply add

1
map.resources :users

to your routes.rb file.

This adds a whole bunch of new helpers too that you use to construct the URLs you need to use, such as

1
2
edit_user_path(@user)
new_user_path(@user)

Theres a catch though when using AJAX calls - you need to also add :method => :GET (or POST etc..) - I see this as a bit of a hack and hopefully it will be more elegant in future. See the API for more information.

To get up to speed on using restul routes DHH's rails conf keynote of 2006 is good viewing - although some of the code examples given are out of date since it was added to core rails.

This PDF is also a worthwhile read.

Filed Under: Rails | Tags:

Comments

Have your say

A name is required. You may use HTML in your comments.