views:

16

answers:

1

Hi,

I have a ruby-on-rails application and I'm now wondering why RoR uses Restful Requests: eg. if you want delete an ressource it's a best practice to do it with such an HTTP Request:

DELETE /entry/13

you can also do it with with such an normal request: GET /entry/delete/13 or GET /entry/13/delete

now my question: when i make a link to such an restful delete operation with the link_to helper

link_to :controller =>:delete, :id => id, :method => :delete

it results in some cryptic javascript:

<a href="/entry/13" 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);var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'GIep/wk5+6EMX23qY4TAP7joKy/G3f5uvMI6d6n9vlA='); f.appendChild(s);f.submit();return false;">Delete</a>

So whats the idea behind it? In my opinion you just exclude non-javascript users.

A: 

All versions of Rails < 3 use very obtrusive javascript (and the result is pretty ugly, as you've demonstrated).

The doc suggests the method will fall-back to using GET if javascript is disabled:

:method => symbol of HTTP verb - This modifier will dynamically create an HTML form and immediately submit the form for processing using the HTTP verb specified. Useful for having links perform a POST operation in dangerous actions like deleting a record (which search bots can follow while spidering your site). Supported verbs are :post, :delete and :put. Note that if the user has JavaScript disabled, the request will fall back to using GET. If you are relying on the POST behavior, you should check for it in your controller‘s action by using the request object‘s methods for post?, delete? or put?.

Either way, I would suggest you create the "destroy" links like so:

# when you have an "entry" object
link_to "Destroy", entry, :method => :delete

# when you only have an "entry" object's id
link_to "Destroy", entry_path(:id => id), :method => :delete
vegetables
thank you very much! :)
Weidling C