small medium large xlarge

Generic-user-small
02 May 2008, 19:55
Michael Curtis (2 posts)

For some reason, the id=”current_item” only gets set the second time I add an item to a cart. The first time it just gets placed in a naked <tr> tag.

Anybody see something wrong with my code?

cart.rb

  def add_product(product)
    current_item = @items.find {|item| item.product == product}
    if current_item
      current_item.increment_quantity
    else
      @items << CartItem.new(product)
    end
    current_item
  end

store_controller.rb

  def add_to_cart
    begin
      product = Product.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("Attempt to access invalid product #{params[:id]}")
      redirect_to_index("Invalid product")
    else
      @cart = find_cart
      @current_item = @cart.add_product(product)
      respond_to { |format| format.js }
    end
  end

_cart_item.html.erb

<% if cart_item == @current_item %>
  <tr id="current_item">
<% else %>
  <tr>
<% end %>
  <td><%= cart_item.quantity %>&times;</td>
  <td><%= h(cart_item.title )%></td>
  <td class="item-price"><%= number_to_currency(cart_item.price) %></td>
</tr>

add_to_cart.js.rjs

page.replace_html("cart", :partial => "cart", :object => @cart)

page[:current_item].visual_effect :highlight,
                                  :start_color => "#88ff88",
                                  :end_color => "#114411"
Samr_small_pragsmall
04 May 2008, 00:18
Sam Ruby (634 posts)

The else clause in “cart.rb”:http://media.pragprog.com/titles/rails3/code/depot_m/app/models/cart.rb should read:

current_item = CartItem.new(product)
@items << current_item
Generic-user-small
04 May 2008, 17:58
Michael Curtis (2 posts)

That did it, thanks for the reply!

You must be logged in to comment