Forum: Ruby on Rails Cannot see what I have done wrong.

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.
171ea139761951336b844e708d1547ab?d=identicon&s=25 James B. Byrne (Guest)
on 2006-01-30 21:46
(Received via mailing list)
In the Agile Rails tutorial I am revisiting building a cart. I have
followed the steps given in the book to create the class 'Cart'
thus:

class Cart

  attr_reader :items
  attr_reader :total_price

  def add_product(product)
    @items << LineItem.for_product(product)
    @total_price += product.price
  end

  def initialize
    @items = []
    @total_price = 0.0
  end

end
~
"app/models/cart.rb"

I have wired together the other bits in
app/controllers/store_controller.rb and app/models/line_item.rb

class StoreController < ApplicationController

  def add_to_cart
    product = Product.find(params[:id])
    @cart = find_cart
    @cart.add_product(product)
    redirect_to(:action => 'display_cart')
  end

  def display_cart
    @cart = find_cart
    @items = @cart.items
  end

  def index
    @products = Product.salable_items
  end

private

  def find_cart
    session[:cart] ||= Cart.new
  end

end
~
"app/controllers/store_controller.rb"
*******

class LineItem < ActiveRecord::Base

  belongs_to :product

  def self.for_product(product)
    item = self.new
    item.quantity = 1
    item.product = product
    item.unit_price = product.price
    item
  end
end
~
"app/models/line_item.rb"
*****

When I attempt to add an item from store/index.rhtml I get this:


> NoMethodError in Store#add_to_cart
>
> undefined method `add_product' for #<Cart:0xb7838a68
> @total_price=0.0, @items=[]>
>
> RAILS_ROOT: script/../config/..

I have successfully completed this part of the tutorial at least
three times now and I cannot for the life of me see what I have
done differently this time.  Can another pair of eyes see what I
cannot?

Regards,
Jim

--
     *** e-mail is not a secure channel ***
mailto:byrnejb.<token>@harte-lyne.ca
James B. Byrne                Harte & Lyne Limited
vox: +1 905 561 1241          9 Brockley Drive
fax: +1 905 561 0757          Hamilton, Ontario
<token> = hal                 Canada L8E 3C3
F98e8bbc010d8ff9818c2f46319b86cc?d=identicon&s=25 Dominique Plante (Guest)
on 2006-01-30 22:22
One thing which may help is:

To make also make sure that in LineItem you have:
belongs_to :product
F98e8bbc010d8ff9818c2f46319b86cc?d=identicon&s=25 Dominique Plante (Guest)
on 2006-01-30 22:22
Oops!!!

I meant:

belongs_to :cart

Dominique Plante wrote:
> One thing which may help is:
>
> To make also make sure that in LineItem you have:
> belongs_to :product
This topic is locked and can not be replied to.