没有数据库的可排序列表

时间:2009-06-12 15:35:25

标签: ruby-on-rails ruby

我有一个使用会话的虚拟购物车(存储在数据库中的会话)。 我使用AJAX调用将产品添加到购物车。此列表也是可排序的。 鉴于购物车是虚拟的,我遇到的问题是更新购物车中产品的分拣位置。任何人都可以提供帮助(特别是sortable_element:update操作)。以下是一些代码:

#cart.rb

class Cart
  attr_reader :items   

  def initialize
    @items = []
  end

  def add_product(product
    @items << CartItem.new(product)
  end
end

#cart_item.rb

class CartItem
  attr_reader :product

  def initialize(product)
    @product = product
  end

  def name
    @product.name
  end
end

#cart/index.html.erb

<div id="items">
  <%= render :partial => 'cart', :object => @cart %>
</div>

#cart/_cart.html.erb

<%= render :partial => 'cart_item', :collection => @cart.items %>
<%= sortable_element "items", :url => {:action => :update} %>

#cart/_cart_item.html.erb

<% content_tag_for :li, cart_item do %>
  <p><%= cart_item.name %></p>
<% end %>

#cart_controller.rb

def index
  find_cart
end

def update
  #???? how does I change the sort of @cart?
  render :nothing => true
end

def find_cart
  session[:cart] ||= @cart
end

1 个答案:

答案 0 :(得分:2)

看看这个解决方案,我认为它会做你需要的

Sort a list of objects by using their attributes in Ruby