views:

109

answers:

3

I have a virtual shopping cart using sessions (sessions stored in the DB). I add products to the cart using an AJAX call. This list is also sortable. The problem I am having is updating the sort position of the products in the cart, given that the shopping cart is virtual. Can anyone help (specifically with the sortable_element :update action). Here is some of the code:

#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
A: 

This railscast explains how to change the sort position in the database the proper way. what does your controller action that handles the sorting look like? If you aren't sorting by a position column in the database, you'll still have to pass the reordered array back to the controller to update the session variable or whatever it is you're using to store the items. so the process is going to be quite similar either way.

Chris Drappier
I looked at that railscast already but I am no further on with executing it, as this isn't linked to the BD just yet. What is the new array? params[:cart] ?
Cameron
+1  A: 

look at this solution, I think it will do what you need

http://stackoverflow.com/questions/852705/sort-a-list-of-objects-by-using-their-attributes-in-ruby

Aaron Saunders
Useful thanks for that.
Cameron
A: 

I have exactly the same problem. Did you ever get this thing solved? Mind sharing your solution?

Arwed