RubyFlow The Ruby and Rails community linklog

Unobtrusive object deletion in Rails, the easy way

Out of the box, Rails requires a HTTP DELETE request to process object deletion, but this requires JavaScript or a form, which isn’t ideal. A few simple changes can improve this situation, for the concise solution continue reading unobtrusive object deletion in Rails…

Comments

For christ’s sake, don’t use GET for destroy-operation! Use at least POST, works without JS, too.

Roland, my article nowhere suggests you should use GET, it routes GET requests to a ‘delete’ action which you should use merely to display a deletion form - not actually delete the object.

What I suggest (in the article) is that you setup DELETE requests to /collection/id/delete are mapped to the ‘destroy’ action, that way, if you have JS enabled, the DELETE request will be handled by JS, if you do not have JS enabled, it will display the deletion form. Either way you do not have any CSRF issues.

I have updated the article to clarify this issue, with a warning, it reads:

“Note: this action SHOULD NOT process the deletion, merely display a form (a confirmation) which the user must submit manually. Otherwise you will run into CSRF attacks.”

This isn’t novel. People have suggested similar concepts since rails started getting restful back in 1.2.6

Nice article, no doubt the other commenters even bothered to your article before leaving a comment. We used this approach recently, its a great fallback for when the user has javascript disabled.

Anonymous Coward, 100% agreed.

A lot of people have their own solutions, I just thought it was worthwhile sharing a very straight-forward solution. A lot of people setup a delete action containing the confirmation form, but then either don’t bother with the JavaScript or implement a more complicated workaround where they alter the link to point to the standard destroy route.

This way allows you to keep the standard Rails JS enhancement (requiring little extra view code), whilst making it unobtrusive. I suppose a further enhancement could be to use the recently added view inheritance functionality and create one standard ‘delete’ view - I might add that to the article.

And, thank you Luke.

It’s not just CSRF you’re protecting yourself from, link prefetchers are another good example. GET should always be safe. Does no-one remember the Google Web Accelerator fiasco?

This seems like a lot of work just so that you can have a link rather than a submit button.

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in