How Does Rails 3's "data-method='delete'" Degrade Gracefully?
Asked Answered
S

4

36

Rails 3 does some cool stuff to make Javascript unobtrusive, so they've done things like this:

= link_to "Logout", user_session_path, :method => :delete

..converts to

<a href="/logout" data-method="delete" rel="nofollow">Logout</a>

But it just occurred to me.. When I turn off javascript the method isn't DELETE anymore, it's GET as expected. So are there plans to, or is there some way to, allow these data- attributes to degrade gracefully, so that link still is a DELETE request?

Stark answered 11/5, 2010 at 8:46 Comment(0)
D
37

The change they made in Rails 3 with these data- attributes wasn't about graceful degradation, it was about unobtrusive JavaScript.

In Rails 2, specifying :method => :delete on a link would generate a whole bunch of inline JavaScript that would create a form with a hidden input and then submit the form. That was the same as it is now: turn off JavaScript and it defaults to a GET request. As such, supporting the case of no JavaScript is the same as it was before.

One option is to use a form/button instead of a link so you can include the method as a hidden field, much like the Rails 2 JavaScript does. Another option is to have the GET version take you to an intermediate page which in turn has the form/button.

The benefit of the new approach is that it's unobtrusive. The JavaScript for changing the HTTP verb exists in an external file and uses the data- attributes to determine which elements it should be attached to.

Dimitry answered 11/5, 2010 at 9:21 Comment(0)
E
21

Rather than using the link_to method -- which would require you use JavaScript to ensure that the HTTP method is DELETE -- use the button_to method, which will create a form with a hidden input element which tells Rails to treat the HTTP method as DELETE rather than POST. If necessary, you can then use CSS to style the button in the form so that it looks like a link.

Enforce answered 18/5, 2011 at 21:19 Comment(1)
This worked for me when the link itself was loaded after the fact via JavaScript, preventing Rails from replacing it with the form. I presume button_to worked because it turns it into a form on the Ruby side of things instead of with JavaScript after the page is loaded. I'd never heard of button_to before, so thank you!Inviting
M
4

The only chance you have is define a form. A link can't be a POST with _method="delete" without Javascript or by form.

Muir answered 11/5, 2010 at 9:14 Comment(1)
it can have query string ?_method=deletePhosphaturia
N
1

It is not possible without javascript.

I make a small jQuery plugin for converting data-method link attribute to pseudo hidden forms (used in laravel project for example).

If you want to use it : https://github.com/Ifnot/RestfulizerJs

Negrete answered 19/2, 2014 at 14:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.