Forum: Ruby on Rails Problems with sample code from "agile webdev. w. rails"

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Andreas S. (Guest)
on 2006-02-01 21:49

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'

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
Siva J. (Guest)
on 2006-02-02 19:04
(Received via mailing list)
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 topic is locked and can not be replied to.