I have a Rails app where I was doing a general delete dialog with "are you sure" before it gets deleted. That's all fine, but I also have a small ajax开发者_JAVA技巧 on click to remove the block containing all the information. The block gets removed no matter what which makes things confusing. I couldn't seem to find any documentation online on how to conditionally execute an action after the confirm symbol.
My code looked like this:
<%= link_to_remote "Delete", :url =>
{:controller => "pixel", :action => :destroy, :id => pixel.id},
:onclick=>"$(this).up(0).remove()" %>
Thanks!
Can you post your code? I'd imagine something like this would work:
link_to_remote("Delete item", :url => item_path, :method => 'delete', :confirm => 'Are you sure?')
I don't have time to pursue an example right now, but try using the :complete
option to link_to_remote
to remove the element after the action completes, instead of :onclick
.
http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M001645 - look at the "callbacks" section.
It's probably as simple as:
<%= link_to_remote "Delete", :url =>
{:controller => "pixel", :action => :destroy, :id => pixel.id}, :confirm => "You sure?",
:complete =>"$(this).up(0).remove()" %>
Can I make a small suggestion, using routes which are based on the default routes (controller, method, id) should ideally not be used, instead use named routes or the proper restful routes given for free when you declare your routes (eg. map.resources :pixels)
I would highly recommend reading the rails routing guide, its a great digest of what can be done and how to do it.
As for your question, what you are trying to achieve is all based on obtrusive javascript. Thats not to say that the link_to_remote
method isn't great, but it certainly outputs messy code if you are displaying a list. I would be cleaner a nicer, in my opinion, to first implement a working example with no javascript then add the javascript unobtrusively. Does this add overhead? yes, but your code will come out cleaner and allow you to easily add extra logic (like removing the row you have deleted) without having to duplicate the functionality on every line.
Sorry but I do not have enough time to provide examples, but a simple google search for unobtrusive javascript rails yields many many results, but here is one to get you started.
Hope this helps, even though its a bit off topic :)
精彩评论