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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
21092e72c89efa62af65eb0007310052?d=identicon&s=25 Andreas Schneider (elmoman)
on 2006-02-01 20:49
Hello,

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
  end

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

end
#-------------

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

#----------------
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:in
`add_to_cart'
Request

Parameters: {"id"=>"2"}

Show session dump

Response

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
Andreas
33bb150cf13d87bce4e80569ca317647?d=identicon&s=25 Siva Jagadeesan (Guest)
on 2006-02-02 18: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




--
Rgds,
--Siva Jagadeesan
http://www.varcasa.com/
My First Rails Project.
Education Through Collabration
This topic is locked and can not be replied to.