Delete database row in ROR - ruby-on-rails

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.

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.

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:
Rails on Rack
How do forms with PATCH, PUT, or DELETE methods work?
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.

Related

Rails link_to :method => :put send a GET request

I'm trying to use link_to to send PUT request but every time i send a GET request instead.
I tried :
<%= link_to raw('Valider'), roommates_join_path(:reference => var['reference']), :method => :put, :class => "btn btn-primary" %>
in my browser I get :
<a class="btn btn-primary" data-method="put" href="/roommates/join" rel="nofollow">Valider</a>
my routes.rb:
put 'roommates/join'
When I click :
No route matches [GET] "/roommates/join"
I have the same problem where I use link_to path, method: :put, data: {} and it fire AJAX to GET and PUT.
Change the link_to to button_to to use the actual form instead of using jquery_ujs fixes the problem. Though, I did not really find put the is the cause.
Make sure you include your application's javascript in your layout.
For example, if you are using the default 'application' layout, ensure you include the application javascript in your <head/> like so:
app/views/layouts/application.html.erb
<head>
...
<%= javascript_include_tag "application" %>
...
</head>

link doesn't ask for confirmation with :confirm

I'm trying to setup a link that deletes a database entry, and everything works as intended, it just doesn't ask for confirmation first. I think I've done everything right, I'm testing this in firefox on ubuntu.
<%= link_to "Delete", #post, :confirm => "Are you sure you want to delete?", :method => :delete %>
any help is appreciated.
Read the documentation carefully:
:data - This option can be used to add custom data attributes.
Data attributes
confirm: 'question?' - This will allow the unobtrusive JavaScript driver to prompt with the question specified (in this case, the
resulting text would be question?. If the user accepts, the link is
processed normally, otherwise no action is taken.
Your link_to should be like this:
<%= link_to "Delete", #post, data: { :confirm => "Question?", :method => :delete } %>
Look at this if you use a version before 4.0.2
Do you have this lines in your application.js file ?
//= require jquery
//= require jquery_ujs

Issue with using link_to :remote - Rails 3

I am using link_to :remote to update one of the div elements on the HTML. This is just a beginner's code. However, the update does not occur on clicking the link. Here is the code:
class SampleController < ApplicationController
def updater
render :text => Time.now
end
end
this is the list.html.erb:
<script type = "text/javascript" src = "/javascripts/prototype.js">
<%= link_to "Hello Testing",
:update => "test_id",
:url => {:action => 'updater'},
:remote => true
%>
<div id="test_id"></div>
So on click the link "Hello Testing", the URL in the browser changes to:
http://localhost:3000/samples?remote=true&update=response_id&url[action]=updater
However, the div element that I am trying to set to the current time does not occur on the UI. What can be the issue here?
Updated the post with:
routes.rb: http://pastebin.com/wmKsa1DD
Generated HTML Code : http://pastebin.com/stU3FpL8
HTML Response in Firebug: http://pastebin.com/WjsB7zAh
Using url_for does not change the behaviour.
please use url_for:
<%= link_to "Hello Testing", url_for(:action => :updater),
:update => "test_id", :remote => true %>
I'm not 100% sure, but I don't think that :update is going to work, since Rails3 now mainly relies on ujs.
The "rails way" to update your div would look like (jquery) :
$('div#test_id').bind('ajax:complete', function(event, xhr) {
$(this).html($.parseJSON(xhr.responseText));
})
1: You should include also rails.js file. Ordinary in Rails it makes like this:
<%= javascript_include_tag :defaults %>
2: I prefer to use this naming for urls: updater_samples_path or [:updater, :samples]
3: You should show your routes. If updater method using not GET method, then you should define it:
<%= link_to "Hello Testing", :update => "test_id", updater_samples_path, :method => :put, :remote => true %>
4: Use FIREBUG to se your AJAX responses. So you can easily debug your app. Also you can show us its response, so we will better understend situation

link_to delete url is not working

I have the following link_to delete url in my app
<%=link_to "Delete",blog_path(#blog.id), :method => :delete, :class => "delete", :confirm => "Are you sure ?"%>
It does not seem to be working.When I click this url, it just takes me to the show path.Can someone please tell me how to fix this. Thanks.
Are you using jQuery? If so, I think the problem could be that you are using jQuery without the updated rails.js file.
Download rails.js here:
https://github.com/rails/jquery-ujs/raw/master/src/rails.js
Drop it in your javascripts directory, overwriting the rails.js that comes default with rails.
Add a javascript include line to include it.
<%= javascript_include_tag "rails" %>
Put this after your Jquery include tag. You probably also want to disinclude the javascript defaults if you don't plan on using prototype.
I included jQuery UI in my application, I found that delete is now working as show, but after doing above Resolved Issue.
Make sure these lines appear in application.js :
//= require jquery
//= require jquery_ujs
Ensure that you have java script turned on. Otherwise :method => :delete acts just as show in Rails.
If you're using restful routing for blogs, then the following should work:
<%= link_to "Delete", #blog, :method => :delete, :confirm => "Are you sure ?"%>
You can try with 'data-method' instead of :method.
<%=link_to "Delete",blog_path(#blog.id), 'data-method' => :delete, :class => "delete", :confirm => "Are you sure ?"%>
You can check on jquery_ujs.js the following piece of code:
// Handles "data-method" on links such as:
// Delete
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.
you should use
<%=button_to "Delete",blog_path(#blog.id), :method => :delete, :class => "delete", :confirm => "Are you sure ?"%>
It's possible to have a working link_to without jQuery
I've found the best process to make a working delete link for ruby on rails without jQuery! Here I already make an answer: https://stackoverflow.com/a/67710994/14387700
But for making this easy, I'm writing this here again.
We need to work with 3 things:
Adding destroy method in articles_controller.rb
routes.rb setup
LINK_TO tag
Let's Start...
Adding destroy method in articles_controller.rb
At first, we will add def destroy ... end in articles_controller.rb,
lets open:
# app/controllers/articles_controller.rb
def destroy
#article = Article.find(params[:id])
#article.destroy
params[:id] = nil
flash[:notice] = "Art has been deleted"
redirect_to :action => :index
end
Here
in the 1st line, we're calling a variable '#article' which will find and select the ID parameters of the article on rails console from our database. Then,
in 2nd line, the #article variable will make the destroy command in the console. then,
in 3rd line: the id params will be deleted and
in 4th line, a notice will flash in application page "Art has been deleted" and also will show in console that, found nothing in the database.
In 5th line, after the destroying process completed, we will be redirected to the article index page.
This is the main factor which will give the destroying command. and make the link_to working.
Setup routes.rb
BUT WAIT
We need 2 routes for the destroy page which are:
A GET protocol setup
A DELETE protocol setup
In routes just add:
resources :articles, except: [:destroy] # this will add all get request links automatically except destroy link
post '/articles/new' => 'articles#create'
post '/articles/:id' => 'articles#update'
post '/articles/:id/edit' => 'articles#update' # this 3 lines are needed for other forms purpose
# we need this 2 lines for our delete link_to setup
delete 'articles/:id/delete' => 'articles#destroy', as: 'articles_delete'
get '/articles/:id/delete' => 'articles#destroy'
Here
The 2nd last line is declaring the DELETE method,
'articles/:id/delete' will be the link structure in post link tag (known as: anchor tag in HTML) for every single post,
'=>' is pointing the link structure to the controller tag which is 'articles#destroy',
then we defined the path text by setting ** as: 'articles_delete'** which we will use as:
'articles_delete_path' or 'articles_delete_url' in link_to tag.
Then
in last line, we defined the get request for the delete link which will give us a working link like "https://2haas.com/articles/1/delete" except "/articles/1/destroy" that means we can customize our delete link from this 2 methods setup with more additional information..
Last sweetest delete output
The desired link_to tag
we can use this to get proper delete link_to tag which will work.
<%= link_to 'Delete Article', articles_delete_path, method: :delete %>
<%= link_to 'Delete Article', articles_delete_url, method: :delete %>
<% obj.each do |post| %>
<%= link_to 'Delete Article', articles_delete_path(post), method: :delete %>
<% end %>
AND that's done except jQuery
Thanks for reading this answer properly.!
HAPPY PROGRAMMINGS

Rails 3 link_to (:method => :delete) not working

I'm having trouble with my verbs in Rails...
viewing a page for a resource (Dog) which has_many (Fleas). Embedded in dog's show.html.haml is a call to render #dog.fleas which automatically(?) finds & uses the template in "fleas/_flea.html.haml" to list each flea associated with said dog.
this displays correctly. whew! Now, next to each flea I've put a "Kill Flea" link that goes to a url: //localhost:3000/dogs/1/fleas/7. Which is generated by:
= link_to("Kill Flea", [ flea.dog, flea ], :method => :delete, :confirm => "Sure? A bunny will die")
but every time that link is clicked there is no confirmation... and it renders the flea's show.html page. it's as if it's using GET on /dogs/1/fleas/7 instead of DELETE?!?
ps- not worried about spiders & robots deleting things in my database... i'm just trying to learn Rails..and understand what's happening
Rails 3 uses unobtrusive javascript now. In Rails 2.3, erb would just shove all that messy javascript right into the link itself, in an onClick event. Now the javascript has been moved out of the link, and into external js files. Make sure you have this in your layout:
<%= javascript_include_tag :all %>
If you do have this, there might be deeper problems keeping your javascript from running, but this is the place to start. Let me know how it turns out.
Hi you can also try this:
application.html.erb:
<%= javascript_include_tag 'jquery_ujs' %>
OR
<%= javascript_include_tag "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", "jquery.rails.js" %>
Check your <%= javascript_include_tag %> in application.html.erb
Perhaps you are missing the "application" js
It must look at least like
<%= javascript_include_tag "application" %>
Here I am not using the javascript_include_tag :all, :application etc.
I am using my own js files, with another custom name: javascript_include_tag :my_custom_file and I also had this issue. And I am not using '= require jquery' in the file, but javascript/jquery is working. I think Rails includes jquery by default. What I done is I changed the
link_to "Logout", destroy_user_session_path, :method => :delete
to
form_tag destroy_user_session_path, :method => :delete, :id => "logout_form"
link_to 'Logout', "#delete", :onclick => "$('#logout_form').submit();"
Now its working fine.
check if application.html.erb
<%= javascript_include_tag :application %>
not as:
<%= javascript_include_tag :default %>
Looks like your link_to method isn't quite right. Try using this code instead:
<%= link_to 'Kill Flea', [flea.dog, flea], :confirm => 'Sure?', :method => :delete %>

Resources