问题
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.
回答1:
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.
回答2:
My problem was that I did not reference jquery. Adding //=jquery
fixed it.
回答3:
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
来源:https://stackoverflow.com/questions/9657295/following-ruby-on-rails-tutorial-and-getting-destroy-users-doesnt-work