small medium large xlarge

Generic-user-small
06 Dec 2010, 23:01
Andy Bolger (2 posts)

Hello,

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

Generic-user-small
07 Dec 2010, 01:30
Luke Burns (3 posts)

Same problem.

AddQuantityToLineItem migration isn’t updating default => 1. I just added it to the model.

To display item.quantity:

<% item.quantity %> BAD <%= item.quantity %> GOOD

Generic-user-small
07 Dec 2010, 01:45
Luke Burns (3 posts)

Ok, so I rolled back the database then called the migration again and it was updated with default => 1.

Generic-user-small
07 Dec 2010, 21:30
Andy Bolger (2 posts)

Thanks Luke, that worked a treat.

You must be logged in to comment