rails 3 - link_to to destroy not working - ruby-on-rails

I am trying to create a destroy link to my users controller, I am also using devise.
Here is my code -
View
<%= link_to 'Delete User?', child, :confirm => "Are you sure you want to delete #{child.full_name}?", :method => :delete, :class => "user-additional", :style => "font-size:12px;font-weight:normal;" %>
Controller
def destroy
if #user = User.find(params[:id])
#user.destroy
respond_to do |format|
format.html { redirect_to account_index_path }
format.xml { head :ok }
end
end
end
Routes
devise_for :users
resources :users, :except => [:new]
The link translates to localhost:3000/users/10
When clicked this opens the users show instead of deleting them
Any ideas ?

Destructive actions should be performed as a form submission - http://www.w3.org/2001/tag/doc/whenToUseGet.html#checklist
use button_to (passing a :method => :delete) instead and style the button appropriately.

Actually I just had the exactly same problem yesterday
Try this:
<%= button_to "delete", your_object, :method=>:delete, :class=>:destroy %>
It works (for me at least)

In case that you are using jQuery instead of Prototype, you are probably missing a javascript file.
You can find details on how to add it to your project from the jquery-ujs GitHub page or from episode 205 of the Railscasts.

At a guess I think it is because in Rails 3, unobtrusive javascript is now used for functionality such as this (Rails 2 would output a bunch of nasty inline javascript for your code, Rails 3 puts the javascript in an external file, and uses HTML5 data- attributes to interact with that.)
To solve this you need to include <%= csrf_meta_tags %> in your page header to reference the external javascript. It also deals with XSS issues.
Some details here: Delete link sends "Get" instead of "Delete" in Rails 3 view

If you are using jQuery, make sure you have something like this:
<script type="text/javascript">
// this allows jquery to be called along with scriptaculous and YUI without any conflicts
// the only difference is all jquery functions should be called with $j instead of $
// e.g. $jQ('#div_id').stuff instead of $('#div_id').stuff
var $jQ = jQuery.noConflict();
</script>

follow the steps in the installation part rails/jquery-ujs
add <%= javascript_include_tag "application" %> in your layout file.

If you haven't included jquery and jquery-ujs in your app , the default link_to default coming with scaffold wont work!
I had the same issue.It got solved after including both these js!

Also if you get this problem in production mode, it may be because you have not compiled the assets. See http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets

Worked for me with confirmation message.
<%= button_to 'Destroy', {action: :destroy, id: version.id}, onclick: 'return confirm("Are you sure?")', method: :delete %>

Related

Following Ruby-on-Rails tutorial and getting 'destroy users' doesn't work

I've recently installed Ruby on Rails 3.2 and have been trying to learn it. I've been following along with the RoR 3.0 tutorial (http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users#top) and so far it is going well (yes I know there's a 3.2 version).
Currently I am stuck on section 10.4.2 which teaches how to add a link to destroy users. It says to add the code
<%= link_to "delete", user, :method => :delete, :confirm => "You sure?",
:title => "Delete #{user.name}" %>
As well as adding in apps/view/layout/application/html/erb
<%= javascript_include_tag :defaults %>
It seems like this should take it right to the destroy method in the user controller, as the tutorial says but it is not working for me and I cannot figure out why. The link it creates is just to /user/:id. I looked at the same section in the 3.2 tutorial and it is fairly the same directions (but does not have the javascript include tag code). I can't get it to work following that tutorial. So I am not sure why it is not working or how to get it to work.
So we are clear, rather than going to the destroy method in this User controller, it goes to /user/:id which is the show method.
Deleting a resource (a user in your case) requires jquery_ujs javascript file to be included on a page. It is quite common to see a 'show' action being called, because without jquery_ujs is not sending the hidden data that indicates the HTTP DELETE verb.
Try to explicitly insert the jquery_ujs like follows:
<%= javascript_include_tag 'jquery_ujs' %>
and see what happens.
jquery_ujs is designed to be '... unobtrusive scripting support file for the Ruby on Rails framework, but is not strictly tied to any specific backend.'. In other words, it scans the document, sees the special data-* attributes and performs various actions depending on these attributes, for example, appending hidden html elements, performing ajax requests, etc.
Also note, that in order to use jquery_ujs, jquery should be referenced too (before).
Hope this helps.
My problem was that I did not reference jquery. Adding //=jquery fixed it.
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" %>
and your link code should be like this:
<%= link_to "<i class='icon-trash'></i> Delete".html_safe, user, :confirm => "Are you sure you want to delete this user? " + user.name + "?" ,:method => :delete%>
and your controller should have like this:
def destroy
#item = Item.find(params[:id])
if #item.destroy
redirect_to users_path, :notice => "Successfully deleted a user."
else
redirect_to users_path, :notice => "Failed to delete a user."
end
end

default_actions in activeadmin in rails doesnt make "delete" button create destroy link

I have this:
ActiveAdmin.register User do
index do
column :email
column :name
column :role
column "Last Sign In", :last_sign_in_at
column :account
column "Units" do |user|
user.units.count.to_s
end
default_actions
end
The default_actions method should create the show, edit, and delete links. It shows them but the delete link is just a link to the show action:
admin/users/1
Specifications said it should create a delete link.
Dont know why it did that. So I tried an alternative:
column "Delete" do |user|
link_to "Delete", destroy_admin_user_path(user)
end
I get this error:
undefined method `destroy_admin_user_path' for <div class="index_as_table"></div>:ActiveAdmin::Views::IndexAsTable
I even tried adding this in routes:
match "/admin/users/:id/destroy(.:format) " => "admin/users#destroy"
Still got same error.
I included this in application.html.haml:
= javascript_include_tag :all
Still same problems as above.
Thanks for response
This is a bit late but the real real reason your link wasn't working is because you didn't put the :method in your link and instead used "destroy_admin_user_path".
Try this instead:
link_to "Delete", admin_user_path(user), :method => :delete, :data => {:confirm => "Are you sure?"}
This is what works for me, with ActiveAdmin.
I had this problem when I updated the active_admin gem, so I fixed it regenerating the active_admin assets and now the destroy action works fine.
rails generate active_admin:assets
Did you check to see if the full rails.js is added to the javascript? Use firebug to inspect the link and see if it has the data-method attribute. Also inspect the HTTP headers and see if the request is made with DELETE.
If the request is not made using "DELETE" than you have a problem with your javascripts. Check rails.js for integrity and jquery integration. Additionally check your assets.
Could your provide more details about your rails version? Javascripts included in HTML source?
Try another thing, go to assets/javascripts/application.js and add
//= require jquery
to the top if you are running 3.1

Rails 3 - remote delete

In an ERB Rails view
<%= link_to("Destroy", foos_path(1), :method => :delete, :confirm => "Are you sure?") %>
With a link_to like the above you can process the delete for a foo with an ID of 1.
How do make it remote and (a) still control being redirected to a page of my control or (b) call custom JavaScript (the goal of which would be jQuery to refresh a list)
Add :remote => true to the link_to will create a remote link.
In your controller method at the end put
respond_to do |format|
format.js { render "my_method"}
end
You can omit the name of the ajax file if it's the same name as the method.
In my_method.js.erb simply call javascript functions, and you can embed erb ie:
$("#someDiv").load(<%= #some_value $>);
You can redirect to another page using standard javascript/jquery if you choose.

ruby on rails - link_to() problem

I made this link in order to destroy a comment :
  <%= link_to 'Destroy Comment', [comment.post, comment],
:confirm => 'Are you sure?', :method => :delete %>
this suppose to send to the destroy action in the comments_controller.
the problem is that it searches for the 'show' action, Instead of the 'destroy' action :
Unknown action
The action 'show' could not be found for CommentsController
Do you think you know why it does that?
Thanks,
Oded
edit: problem solved I used 'button_to'
Rails 3:
When you use JQuery, make sure you have the right rails.js file (https://github.com/rails/jquery-ujs). When you use Prototype, the correct rails.js file is already installed. Also, make sure the following is added in your layout head:
<%= csrf_meta_tag %>
And also make sure that both the JS framework and the rails.js file is being loaded.
<%= javascript_include_tag "jquery", "rails" %>
# or
<%= javascript_include_tag "prototype", "rails" %>
Just a side-note - You can also point to the Googleapis link: http://scriptsrc.net/.
When you use :method => :delete inside a link, the following HTML will be created:
Click me!
As you see, the HTML5 data- attribute is being used. The rails.js file automaitcally puts click events on links with these attributes. When data-method="delete" is set, the request will be done with the DELETE HTTP method. So clicking it will destroy the comment. Also, setting :confirm will create a data-confirm attribute which does what you would expect.
Rails 2:
When you use Prototype, the :method => :delete thing will work automatically. Just make sure you include the right Javascript files:
<%= javascript_include_tag :defaults %>
When using JQuery you should install the 'jrails' plugin (https://github.com/aaronchi/jrails). It allows you to use the same Prototype helpers for JQuery. The plugin uses an old version of JQuery, so make sure you update that one.
I don't know for sure if the :method attribute uses Prototype in Rails 2 or just regular Javascript. So it could be that you don't even need Prototype or JQuery for the :method attribute in Rails 2.
As I said in the comment: I never use button_to for DELETE links. You can just as easily get it working with link_to. And as far as I know it's the helper most people use when creating these kind of links. Hope it helps. :)
ERROR: ActionController::RoutingError (No route matches [GET] "/javascripts/jquery.js")
Solution, download: http://code.jquery.com/jquery-1.6.3.js
ERROR: AbstractController::ActionNotFound (The action 'show' could not be found for CommentsController)
Solution, download: https://github.com/rails/jquery-ujs/raw/master/src/rails.js
In rails 3.1.0 save the above js files to app/public/javascripts/
Rename or remove your existing js files.
I've just solved this problem in my own App (rails 3). I followed the steps for rails 3 and, the most important issue, installed the correct rails.js file in my public/javascripts folder. It didn't work until I've installed rails.js.
The one i chose is this:
https://raw.github.com/rails/jquery-ujs/master/src/rails.js
I just came across this same issue with Rails 3. I'm using jQuery with the updated rails.js file. What fixed it for me was something simple - use :method => :delete, not :method => :destroy.
=link_to( 'delete account', user_admin_path(current_user.id), :confirm => "Deleting your account is irreversible!! Are you sure you wish to continue?", :method => :delete )
And in the header I have:
= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js", "jquery.colorbox-min", "jquery.validate.min", "rails"
Works like a charm :)
Make sure you reference //= require jquery and //= require jquery_ujs (in that order) in your application.js file, in \app\assets\javascripts.

Generate PDF file using AJAX call

I'm trying to generate a PDF file using AJAX call in Rails3. The following code generates a PDF file which I have created using PRAWN gem.
<%= link_to "Generate pdf", books_path(#book, :format => 'pdf') %>
I do not want user to view the PDF until they order it. So, the goal is to create a PDF file in the server.
Any ideas or thoughts much appreciated.
Use this, make sure your remote action does not return the PDF, but simple generates and stores it on the server.
link_to "Generate PDF", prepare_books_path(#book), :remote => true, :method => :put
This will work in Rails 3. If you're using jQuery, make sure to read this article on how to set things up correctly.
Your controller action may look like this:
def prepare
# Do your thing to generate the PDF
render :text => "PDF Generated", :status => 200
end
I used the PUT-method because you are altering the state of your data (e.g. you are generating something new, you don't want a bot or crawler to automatically call that).
Firstly, it beats me why you would do something on a request like generating a PDF, when the user is not expecting that action. Isn't better to only generate the pdf when the user requests for it?
Thanks Ariejan.
I modified your code as following and it did just what I wanted.
<%= link_to "Generate Story Book", pdfbook_stories_path(:format => 'pdf'), :remote => true %>
And for the controller,
def pdfbook
#stories = current_account.stories
respond_to do |format|
format.pdf {}
end
end

Resources