Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

216 | Chapter 7: REST, Resources, and Web Services


The named routes for singleton resources are similar to those for collections, again
missing only the route to the collection.


Depending on the application, not all of these routes may be used. For example, if
the account is created automatically when the user is created, then thenew,create,
anddestroy actions may not apply.


ActionView Support


The Railslink_tofamily of helpers can take a:methodparameter to define the HTTP
method that will be used when a user clicks on the link. For a method ofPOST,PUT,or
DELETE, the helpers generate JavaScript that creates a hidden inline form, sets up the
appropriate hidden form field for the _methodparameter (as is detailed next in
“Method emulation”), and submits it. The handler returnsfalseso that the link’s
actual target is not followed. For example, the ERb code:


<%= link_to 'Delete', person_path(@person), :method => :delete %>

creates the following link:


<a href="/people/1" onclick="
var f = document.createElement('form');
f.style.display = 'none';
this.parentNode.appendChild(f);
f.method = 'POST';
f.action = this.href;
var m = document.createElement('input');
m.setAttribute('type', 'hidden');
m.setAttribute('name', '_method');
m.setAttribute('value', 'delete');
f.appendChild(m);
f.submit( );
return false;
">Delete</a>

HTTP Rails Semantics
GET /users/1/account/new new Shows a form to create user’s account
POST /users/1/account create Creates the user’s account; redirects to its URI
GET /users/1/account show Shows account information
GET /users/1/account/edit edit Shows an edit form for the account
PUT /users/1/account update Updates the account with the provided data
DELETE /users/1/account destroy Removes the account

Named route URI Params
account_path(1) /users/1/account {:user_id => 1}
new_account_path(1) /users/1/account/new {:user_id => 1}
edit_account_path(1) /users/1/account/edit {:user_id => 1}
Free download pdf