论坛首页 入门技术论坛

学习《应用Rails进行敏捷Web开发》时遇到购物车的问题

浏览 5127 次
该帖已经被评为新手帖
作者 正文
   发表时间:2007-02-23  
在第八章中遇到了对购物车进行操作时出现无法将产品加入到session中,代码如下:

store_controller.rb
---------------------
class StoreController < ApplicationController

  def index
    @products = Product.salable_items
  end
 
  # 添加商品到购物车方法
  def add_to_cart
    # 根据 id 得到一个商品对像
    product = Product.find(params[:id])
    @cart = find_cart
    @cart.add_product(product)
    redirect_to(:action => 'display_cart')
  end
 
  def display_cart
    @cart = find_cart
    @items = @cart.items
  end
 
  private
  def find_cart
    session[:cart] ||= Cart.new
  end
end
------------------------------

cart.rb
------------------------------
class Cart
  attr_reader :items
  attr_reader :total_price
  def initialize
    @itmes = []
    @total_price = 0,0
  end
 
  def add_product(product)
    @items << LineItem.for_product(product)
    @total_price += product.price
  end
end
------------------------------



错误信息
------------------------------
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.<<

#{RAILS_ROOT}/app/models/cart.rb:10:in `add_product'
#{RAILS_ROOT}/app/controllers/store_controller.rb:12:in `add_to_cart'
-e:4:in `load'
-e:4
------------------------------

因为是刚开始学习Rails而且对Ruby都不懂,还请指教!!!
   发表时间:2007-02-23  
自己先把那一章读完好不好?
0 请登录后投票
   发表时间:2007-02-23  
这和读完应该没关系吧,我到这里就已经被卡住了。
0 请登录后投票
   发表时间:2007-02-23  
86页。
ROR不认识Cart是谁。
0 请登录后投票
   发表时间:2007-02-23  
应该如何处理这个问题呢?
我在使用单步调试已经进入到cart.rb文件中了,就是在执行
def add_product(product)
@items << LineItem.for_product(product)
@total_price += product.price
end
这个方法的时候出的错,现在是不知道如何解决这个错误!
书中附带的代码和书上的内容不一致。
0 请登录后投票
   发表时间:2007-02-23  
oksonic 写道
应该如何处理这个问题呢?
我在使用单步调试已经进入到cart.rb文件中了,就是在执行
def add_product(product)
@items << LineItem.for_product(product)
@total_price += product.price
end
这个方法的时候出的错,现在是不知道如何解决这个错误!
书中附带的代码和书上的内容不一致。


删除临时目录下面的session文件,重起webrick
0 请登录后投票
   发表时间:2007-02-23  
能说一下临时文件在哪里吗?

找了网上的资料,我删除了%TEMP%所有文件,并重启webrick,错误依旧。
0 请登录后投票
   发表时间:2007-02-23  
depot\tmp\sessions\

0 请登录后投票
   发表时间:2007-02-23  
我再贴出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

经过一下午的研究,发现就是cart.rb中的
    @items << LineItem.for_product(product)
这一句代码无法通过
0 请登录后投票
   发表时间:2007-02-24  
我把cart.rb的代码修改了一下

class Cart
  attr_reader :items
  attr_reader :total_price
  def initialize
    @itmes = []
    @total_price = 0,0
  end
 
  def add_product(product)
    item = LineItem.for_product(product)
    # 执行到下面这一句出现了问题-------------
    @items << item
    @total_price += product.price
  end
end

ruby 中的"<<"是做什么用的?我手上的三本书都没有介绍过.
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics