Problems with sample code from "agile webdev. w. rails"


I am veeeery new to rails and also to ruby. I have 2 books here on my
desk and try to go through it.
The first book is “Agile Webdevelopment with Rails” and I have trouble
with the following code which I have from the book. I cant get it
working. I searched a lot on google - and also on the erata pages of the
book publisher but without any luck. I hope someone can help me.

here is the complete Cart class (cart.rb file)

class Cart
attr_reader :items
attr_reader :total_price

def initialize
@items = []
@total_price = 0.0

def add_product(product)
item = @items.find { |i| == }
if item
item.quantity += 1
item << LineItem.for_product(product) # <<<<<<<< this is line
@items << item
@total_price += product.price


I get the following error when I want to add a product to the shopping

NoMethodError in Store#add_to_cart

You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.<<
RAILS_ROOT: script/…/config/…

Application Trace | Framework Trace | Full Trace
#{RAILS_ROOT}/app/models/cart.rb:17:in add_product' ./script/../config/../app/controllers/store_controller.rb:11:inadd_to_cart’

Parameters: {“id”=>“2”}

Show session dump


Headers: {“cookie”=>[], “Cache-Control”=>“no-cache”}

What I can say from my less knowledge of rails is, that ‘item’ seams to
be nil and this causes an error

i would be happy if someone can give me a tip - I cant find a solution
thanks a lot

Check using IRB…or look at database whether u have that Line Item.

Also I notice u have another error in your code. Try to solve it

NoMethodError in Store#add_to_cart

–Siva J.
My First Rails Project.
Education Through Collabration

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs