쇼핑카트 데모보기


# 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 => "" %>
    <%= 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? %>

신고
Posted by The.민군


티스토리 툴바