I’m new to Ruby on Rails and am working my way through the book, building the shopping cart. I have hit a bit of a snag with cart item quantity.
My question is: Where is the initial quantity set that is displayed in the cart view <%= item.quantity %> ?
Currently, I can’t get the quantity to display when I add a single item to the cart i.e. the cart displays × Web Design for Developers when it should display 1 × Web Design for Developers. When I add a second item I get the following error message NoMethodError in Line itemsController#create
You have a nil object when you didn’t expect it! You might have expected an instance of Array. The error occurred while evaluating nil.+
I’ve hacked arround this by adding current_item.quantity = 1 to the else statement in cart.rb
class Cart < ActiveRecord::Base has_many :line_items, :dependent => :destroy
def add_product(product_id) current_item = line_items.where(:product_id=>product_id).first if current_item current_item.quantity += 1 else current_item = line_items.build(:product_id => product_id) current_item.quantity = 1 end current_item end end
Any advice would be greatly welcomed. Thanks, Andy