Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails' link_to method: GETing when it should DELETE

I'm following Michael Hartl's Rails Tutorial, and for some reason the following code:

<%= link_to 'delete', user, :method => :delete, :confirm => "You sure?",
                                :title => "Delete #{user.name}" %>

Issues a GET request (as I verified by checking the rails server log). I also verified that the following line is in my application view:

<%= javascript_include_tag :all %>

One thing I didn't quite understand, and it's probably the source of my problem: where is the "delete" method defined? I verified in Hartl's source code that he defines a "destroy" method in the controller, not "delete". But even if I change the link_to to :method => :destroy, it just issues a GET.

I'm using Rails 3.1. Any tips?

like image 859
koggit Avatar asked Sep 19 '11 02:09

koggit


2 Answers

Also check that this is in your application.js:

//= require jquery
//= require jquery_ujs 

Apparently I had the jquery without the jquery_ujs and I had the same problem until I added that.

Note that you may need to add these lines above any import statements within application.js.

like image 100
Jamel Toms Avatar answered Oct 21 '22 11:10

Jamel Toms


Most browsers don't actually support the DELETE verb, so Rails fakes it by modifying the HTML it generates. Rails tacks on a HTML5 attribute called data-method and sets it to "delete". So when a user clicks on the link, it is actually issued as a GET request, but the data-method attribute allows for some Rails magic and means your routing code should recognize it as a DELETE request.

edit:

You can test it yourself in the console. Run bundle exec rails c to get into the console, and look at the HTML that this generates:

helper.link_to "delete", "foobar/delete", :method => 'delete'

The HTML should look like this:

<a href="foobar/delete" data-method="delete" rel="nofollow">delete</a>
like image 21
jergason Avatar answered Oct 21 '22 09:10

jergason