问题描述
undefined method `product' for #<Product:0x48b2c44>在学习<应用Rails进行敏捷Web开发>第八章 迭代C 1 :创建购物车遇到undefined method `product' for #<Product:0x48b2c44>错误NoMethodError in StoreController#add_to_cartundefined method `product' for #<Product:0x4a02900>RAILS_ROOT: ./script/../config/..D:/InstantRails/ruby/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1860:in `method_missing'#{RAILS_ROOT}/app/models/cart.rb:16:in `add_product'#{RAILS_ROOT}/app/models/cart.rb:16:in `each'#{RAILS_ROOT}/app/models/cart.rb:16:in `find'#{RAILS_ROOT}/app/models/cart.rb:16:in `add_product'#{RAILS_ROOT}/app/controllers/store_controller.rb:11:in `add_to_cart'我的cart.rb 文件代码如下lass 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 @items << CartItem.new(product) end end endstore_controller.rb代码如下class StoreController < ApplicationController def index @products = Product.find_products_for_sale end def add_to_cart @cart = find_cart product = Product.find(params[:id]) @cart.add_product(product) end private def find_cart session[:cart] ||= Cart.new end end难道product被系统认成了一个可执行方法,而没有被认成一个对象放在items[]数据中问题补充:我按照书上把session保存到数据库中,现在把session重新生成,问题还是没有解决
解决方案
删除session文件,重起服务器再试试看