small medium large xlarge

Generic-user-small
22 Apr 2009, 00:07
drub (6 posts)

Greetings ADWR fans!

  • Page 107 (print), Figure 8.1
  • jruby 1.2.0 (ruby 1.8.6 patchlevel 287) (2009-03-16 rev 9419) [x86-java]
  • Win XP, SP3

Things are basically working. But, only a single item is displayed in the cart, http://localhost:3000/store/add_to_cart/3, as an example.
* If I navigate back to the store and select the same item again, the cart still only displays quantity 1 * If I navigate back to the cart and select a different item, the cart shows the new item, quantity 1

Am wondering if storing the cart in the session is fouled up. Perhaps a new session is being created each time? Examining the entries in the Session table, it looks like the same value is being entered in the table with each cart access.

Including app/controllers/store_controller.rb. Seems the most likely problem location.

What do I look for? What can be the cause? Where is the likely problem location?

Many thanks!

class StoreController < ApplicationController

  protect_from_forgery :only => [:create, :update, :destroy]

  def index
    @products = Product.find_products_for_sale
  end

  def add_to_cart
    product = Product.find(params[:id])
    @cart = find_cart
    @cart.add_product(product)
  rescue
    logger.error("=== Warning: Attempt to access invalid product #{param
s[:id]}")
    flash[:notice] = "Invalid product"
    redirect_to :action => 'index'
  end


  private

    def find_cart
      # If the hash has a value corrosponding to :cart, return it.
      # Otherwise, return a new Cart object.
      session[:cart] ||= Cart.new
    end

end
~
~
~
Samr_small_pragsmall
22 Apr 2009, 20:41
Sam Ruby (634 posts)

What does add_product look like in app/models/cart.rb ?

Generic-user-small
22 Apr 2009, 22:24
drub (6 posts)

That’s where I looked first. Sure looks consistent with the version in depot_h.

class Cart
  attr_reader :items

  def initialize
    @items = []
  end

  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
  end

end

Late breaking news … It all now appears to work correctly. But why??

Since the first post, I rebooted this XP machine. (Installed Wubi in the hopes of getting a sane dev env).

What is to be learned from this experience? When must the script/server be restarted? Or was it something else? Any thoughts or coaching is greatly appreciated for this noob.

Thank you very much! I am really finding the book extremely useful and enjoyable.

Generic-user-small
06 May 2009, 17:14
James West (104 posts)

Lesson learned is that you should always re-start your server if you experience unexpected results.

This law has saved me a few hours of headaches in the past

You must be logged in to comment