AJAX + degradable way to delete an record

Hi all!

So, following the guides on the depot app, you learn that a good way to create 'Delete' links for records is using link_to and the :method => post so that the request is sent as POST instead of GET, thus not having the 'destructive get request'.

What the depot app would tell you to use is something like:

<%= link_to 'Delete', { :action => 'delete', :id => service }, :confirm => 'Are you sure?', :method => 'post' %>

This works great, etc. But how will I make something like that that generates a XHR request and, if JS disabled, a regular POST request (or GET, as a last resort)?

I think a form_to_remote might not work since I'm using tables to show the records and I've seen it before where it doesn't work unless the form is around the table, and not inside it.

How have you guys managed to do something like it?


It's an interesting question, actually, as RAILS 2 uses the :method => option extensively to make its RESTful magic work, and we are faking not only POST but also PUT and DELETE using javascript.

I just disabled javascript and tried one of my admin sections' destroy links, and it broke, trying to render a page layout that doesn't exist. However, it did mean that trying to follow a delete link without javascript enabled, like a bot would, does not destroy your records.

I believe all that is required to 'pretend' POST/PUT/DELETE from a link is to add _method=post (etc) to the query string. Rails will use this to pretend that it received a POST request when actually it didn't.

so you 'could' fake a POST link by doing <%= link_to 'Delete', { :action => 'delete', :id =>

service, '_method' => 'post' }, :confirm => 'Are you sure?', :method => 'post' %>

so that the non-js version still sent the dummy method. But I haven't tried this and i'm not sure what the rails community wil have to say. Also this makes your GET link destructive again....

Try this for some more enlightened information (i haven't viewed it but their stuff is usually good)

Or you can use


in place of <%=link_to

This builds an actual form tag. Then just style it with CSS to make it look like a link.

#77 Destroy Without JavaScript - RailsCasts?