这是遇到的错误,找了好久没找到问题出在什么地方。 NoMethodError in StoreController#add_to_cart
undefined method `product' for #Product:0xaa46858 Rails.root: C:/Users/malibin/My Documents/Aptana Studio 3 Workspace/shopMe
Application Trace | Framework Trace | Full Trace
app/models/cart.rb:9:in add_product'
app/models/cart.rb:9:in
each'
app/models/cart.rb:9:in find'
app/models/cart.rb:9:in
add_product'
app/controllers/store_controller.rb:9:in `add_to_cart'
这是我的 controller 和 model
class Cart
attr_reader :items
def initialize
@items = []
end
def add_product(product)
current_item = @items.find {|item| item.product == product}
if current_item
current_item.increment_quantity
else
current_item = CartItem.new(product)
@items << current_item
end
current_item
end
def total_price
@items.sum { |item| item.price }
end
def total_items
@items.sum { |item| item.quantity }
end
def total_price
@items.sum { |item| item.price }
end
end
class StoreController < ApplicationController def index @products = Product.find_product_for_sale end
def add_to_cart product = Product.find(params[:id]) @cart = find_cart @cart.add_product(product) rescue ActiveRecord::RecordNotFound logger.error("Attempt to access invalid product #{params[:id]}" ) flash[:notice] = "Invalid product" redirect_to :action => 'index' end
def find_cart unless session[:cart] # if there's no cart in the session session[:cart] = Cart.new # add a new one end session[:cart] # return existing or new cart end #清空购物车 def empty_cart session[:cart] = nil flash[:notice] = "Your cart is currently empty" redirect_to :action => 'index' end
end