Drag and Drop deletion with Rails

I don’t like to do Drag and Drop in Web Applications. I dislike it so much that I never did dnd in Rails, so when a customer explicitly asked for a drag and drop trashcan in an application I had to start looking through rails docs, fearing dozens of Javascript callbacks.

It turned out wonderfully easy, requiring me to add just two lines of code in the view and a short action in the controller:

# This is the line of code I added to the partial that is rendered for each draggable element
<%= draggable_element "#{picture.class}_#{picture.id}", :revert => true, :constraint => "'vertical'" %>
 
# This is the code I added to the trashcan 
<%= drop_receiving_element("trash", :url => {:controller => :immobili, :action => :destroy_image}, :hoverclass => "hover_trash") %>

That’s it, really, the controller action just deletes the element and hides is on the page via a render :update block.

2 Responses to “Drag and Drop deletion with Rails”

  1. François Beausoleil Says:

    I also usually delete the element in the render :update block, after a delay if I’m using effects. This ensures that if the element has any form fields that a subsequent POST won’t send the fields again.

  2. Giovanni Intini Says:

    Thanks for the tip François, I’ll keep it in mind.