I am getting an undefined method error in my cart.rb class when trying
to find in an array. I cannot see what my error is. Perhaps a view
more eyes can help me with this:
#---------------------------------------------------------------
1 class Cart
2
3 attr_reader :items
4 attr_reader :total_price
5
6 def initialize
7 @items = []
8 @total_price = 0.0
9 end
10
11 def add_product(product)
12 # @items << LineItem.for_product(product)
13 item = @items.find {|i| i.product_id == product.id}
14 if item
15 item.quantity += 1
16 else
17 item = LineItem.for_product(product)
18 @items << item
19 end
20 @total_price += product.price
21 end
22
23 end
#--------------------------------------------------------------------
gives this in the stack trace:
/usr/lib/ruby/gems/1.8/gems/activerecord-1.13.2/lib/active_record/base.rb:1501:in
`method_missing''
#{RAILS_ROOT}/app/models/cart.rb:13:in `add_product''
./script/../config/../app/controllers/store_controller.rb:9:in
`add_to_cart''
The only method that I can see called in line 13 is #find since
product_id is a defined column in line_items:
CREATE TABLE line_items (
id bigserial NOT NULL,
product_id bigint NOT NULL,
quantity numeric(10,2) DEFAULT 0 NOT NULL,
unit_price money NOT NULL
) WITHOUT OIDS;
with this as line_items.rb in app/models
#--------------------------------------------------------------------------
1 class LineItem < ActiveRecord::Base
2
3 belongs_to :product
4
5 def self.for_product(product)
6 item = self.new
7 item.quantity = 1
8 item.product = product
9 item.unit_price = product.price
10 item
11 end
12 end
#--------------------------------------------------------------------------
Can anyone provide me with a clue about what I have missed?
Regards,
Jim
--
Posted via http://www.ruby-forum.com/.