I bought the second edition of the ruby on rails, it seems to work fine
now, did some adjustments to the code. But now I get a second error and
I want to learn to understand to fix them myself. So here is the error.
ArgumentError in StoreController#add_to_cart
wrong number of arguments (1 for 0)
#{RAILS_ROOT}/app/models/cart.rb:15:in initialize' #{RAILS_ROOT}/app/models/cart.rb:15:inadd_product’
#{RAILS_ROOT}/app/controllers/store_controller.rb:19:in `add_to_cart’
-e:4
Now, it says as far as I understand it, that it should need 0 arguments
instead of 1. But that should be quite impossible, beacause the cart.rb
has a def add_product(product) as we shall see later. I do not
understand why it gives me that error. Here is the store_controller.rb:
[CODE]
class StoreController < ApplicationController
def index
@products = Product.find_products_for_sale
#creates an instance variable that holds a list of all the
#products in order to make it available to the code in the view
#that will display the table
#find_products_for_sale() IS DEFINED IN product.rb
end
def add_to_cart
@cart = find_cart #we use find_cart method to find (or create)
#a cart in this session
@product = Product.find(params[:id]) #we use the params object
#to get the id parameter
#from the request and then
#call Product model to find
#the product with that id.
@cart.add_product(@product) #add this product to the cart
end
private
def find_cart
unless session[:cart] #if there is no cart in sesssion add one
session[:cart] = Cart.new #add a new one
end
session[:cart] #return existing or new cart
end
end
[CODE]
Also here is the cart.rb
[CODE]
class Cart
include Reloadable
attr_reader :items
def initialize
@items = []
end
def add_product(product)
existing_product = @items.find {|item| item.product == product}
if existing_product
existing_product.increment_quantity
else
@items << Cart.new(product)
end
end
end
[CODE]
And here is the cart_item.rb
[CODE]
class CartItem
include Reloadable
attr_reader :product, :quantity
def initialize(product)
@product = product
@quantity = 1
end
def increment_quantity
@quantity += 1
end
def title
@product.title
end
def price
@product.price * @quantity
end
end
[CODE]