Harry February 2016

Delete database row in ROR

Can someone help me why the following two pieces of code do not yield the same 'result'?

Option 1

<%= button_to 'delete', {:controller => "articles", :action => 'destroy', :id => article.id}, 
  :confirm => "Are you sure you want to delete?", :method => :delete %>

Option 2

<%= link_to 'delete', {:controller => "articles", :action => 'destroy', :id => article.id}, 
  :confirm => "Are you sure you want to delete?", :method => :delete %>

Option 1 works. Option 2 for some reason calls the Show action in the controller. Funny thing is that Option 2 is used in the Ruby On Rails tutorial, which I was following....

As you can imagine I am a novice to ROR.

Answers


Mihai-Andrei Dinculescu February 2016

In order for link_to to work with the delete method, Rails needs the unobtrusive scripting adapter for jQuery.

  • Make sure that your Gemfile has

    gem 'jquery-rails'

  • Make sure that app/assets/javascripts/application.js has

    //= require jquery
    //= require jquery_ujs

  • Make sure that your app/views/layouts/application.html.erb has

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>

    inside the head tag. Remove the 'data-turbolinks-track' => true section if you don't plan to use Turbolinks.


max February 2016

Since browsers can't send natively extended set of HTTP verbs (DELETE, PUT, PATCH). Rails uses the Rack::MethodOverride middleware to fake it.

So when you do a POST request with the _method = DELETE param the request object that your Rails app receives has request.method == 'DELETE'.

Recommended reading:

button_to creates a discrete form. So your "button" is really a form with hidden inputs.

<form action="articles/1" method="post">
  <input type="hidden" name="_method" value="DELETE">
  <input type="submit">This is the button you see</button>
</form>

Also Rails is pretty damn awesome so you can simply do:

<%= button_to 'delete', article, 
  confirm: "Are you sure you want to delete?", method: :delete %>

And it will figure out the route by itself as long as you follow the rails conventions.

link_to uses javascript to enhance a normal <a> element. Instead of the normal behavior the jQuery ujs driver creates a form like the above and submits it.

The most common reason that you get problems with link_to is that you don't have jquery and jquery_ujs included in your application.js or that you have a script error which is preventing it from doing its job. Check the browser console for errors.

Post Status

Asked in February 2016
Viewed 1,409 times
Voted 6
Answered 2 times

Search




Leave an answer