1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
   | # view
<div style="margin-bottom:20px;height:120px;">
<% for product in @products %>
  <%= image_tag "/images/products/product#{product.id}",
        :id => "product_#{product.id}",
        :alt => product.title, 
        :class => "products"  %>
  <%= draggable_element "product_#{product.id}", :revert => true %>
<% end %>
</div>
 
<h2>Your cart:</h2>
 
<div id="cart" class="cart" style="clear:left; height:132px;margin-top:10px;">
  <div id="wastebin">
    Drop items here to remove them from the cart.
  </div>
  <div id="items">
    <%= render :partial => "cart" %>
  </div>
  <div style="clear:both;"></div>
</div>
 
<div style="height:40px;padding-top:10px;">
<p id="indicator" style="display:none;margin-top:0px;">
  <%= image_tag "indicator.gif" %> Updating cart...
</p>
</div>
 
<%= drop_receiving_element "cart", 
      :update => "items", :url => { :action => "add" },
      :accept => "products", :hoverclass => "cart-active",
      :loading => "Element.show('indicator')",
      :complete => "Element.hide('indicator')" %>
 
<%= drop_receiving_element "wastebin", 
      :update => "items", :url => { :action => "remove" },
      :accept => "cart-items", :hoverclass => "wastebin-active",
      :before => "Element.hide(element)",
      :loading => "Element.show('indicator')",
      :complete => "Element.hide('indicator')" %>
 
# controller
class ShopController < ApplicationController
 
  def index
    session[:cart] ||= {}
    @products = Product.find(:all)
  end
 
  def add
    product_id = params[:id].split("_")[1]
 
    session[:cart][product_id] = 
      session[:cart].include?(product_id) ?  
      session[:cart][product_id]+1 : 1
 
    render :partial => 'cart'
  end
 
  def remove
    product_id = params[:id].split("_")[1]
 
    if session[:cart][product_id] > 1 
      session[:cart][product_id] = session[:cart][product_id]-1
    else
      session[:cart].delete(product_id)
    end
 
    render :partial => 'cart'
  end
 
end
 
 
# _cart.rhtml partial
<% session[:cart].each do |product,quantity| %>
<div>
  <% quantity.times do |i| %>
    <%= image_tag "/images/products/product#{product}", 
          :class => "cart-items", 
          :id => "item_#{product}_#{i}", 
          :style => "position:relative;" %>
    <%= draggable_element "item_#{product}_#{i}", :revert => true %>
  <% end %>
  <span class="title">
    <%= Product.find(product).title + " (#{quantity})" %>
  </span>
</div>
<% end %>
<%= "Here's your shopping cart." if session[:cart].empty? %> | 
Partager