Posts Tagged ‘drag and drop’
How to add additional parameters to distinguish Droppables
by Pace on January 3rd, 2008 @ 5:24 pm in
Off-Topic
Tags: ajax, drag and drop, droppable, droppables, rails, ruby, Ruby on Rails, scriptaculous
I’m working on an organizational Ruby on Rails app, code-named “Kyeliblocks”, which is basically a to-do list organized by date. Sort of like a slimmed-down 30 boxes. One of the features of Kyeliblocks is to be able to drag bubbles (to-do items) from one block (calendar day) to another. This was my first time using Rails and script.aculo.us for drag and drop, and I ran into a problem while studying the examples and demos. All the examples, like scriptaculous’s shopping cart demo, had a small fixed number of droppables, so they didn’t need to know which droppable was the target — it was obvious from the action. So I had some code like this to make the bubbles draggable:
<% block.bubbles.each do |bubble| %>
<div class="bubble" id=<%="bubble_#{bubble.id}"%>>
...
</div>
<%= draggable_element "bubble_#{bubble.id}", :revert => true %>
<% end %>
and then in the block view, I made the block droppable like so:
<div class="block" id=<%="block_#{block.id}"%>>
...
</div>
<%= drop_receiving_element "block_#{block.id}",
:update => "kyeliblocks",
:url => { :action => "drag_bubble" },
:accept => "bubble"
%>
Then in drag_bubble.html.erb, my problem became evident:
I just dragged bubble #<%=params[:id].split("_")[1]%> to some block.
I had just dragged the bubble to some block, but I had no way to know what droppable I had just dragged it to! The draggable id was passed into params as :id, but the droppable id was nowhere to be found. I didn’t want to perpetrate a horrible hack like using 14 different copy-and-pasted action names for each of the 14 blocks visible on the page at any given time — the action name was the only way I could see to differentiate the target droppable.
But I was just being completely dense. That’s what every parameter other than :action is for, in the :url hash. All I needed to do was this:
<div class="block" id=<%="block_#{block.id}"%>>
...
</div>
<%= drop_receiving_element "block_#{block.id}",
:update => "kyeliblocks",
:url => { :action => "drag_bubble", :block_id => block.id },
:accept => "bubble"
%>
(note the :block_id parameter on the :url line), and then my drag_bubble.html.erb had all the information it needed, right there in the params hash!
I just dragged bubble #<%=params[:id].split("_")[1]%>
to block #<%=params[:block_id]%>.
Now of course this was just an intermediate step for debugging — I want the action to actually do something instead of just render a template. But I still wanted to share my embarrassingly simple solution with y’all, in case some other Rails noob can save themselves a couple of hours of hair pulling. (:












