I am building the Depot app from Agile. And an hoping someone can
point out the obvious that I cannot see.
** Here is the error - it occurs when I choose the “add to cart” link.
NoMethodError in StoreController#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/…
#{RAILS_ROOT}/app/models/cart.rb:11:in add_product' #{RAILS_ROOT}/app/controllers/store_controller.rb:15:in
add_to_cart’
** controllers/store_controller.rb
class StoreController < ApplicationController
def index
@products = Product.salable_items
end
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
@item = @cart.items
end
private
def find_cart
session[:cart] || Cart.new
end
end
** models/cart.rb
class Cart
attr_reader :items
attr_reader :total_price
def intialize
@items = []
@total_price = 0.0
end
def add_product(product)
@items << LineItem.for_product(product)
@total_price += product.price
end
end
** models/line_item.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.
Thanks
-Stephen