0

老实说,我比以往任何时候都更迷失过。最近,我一直在尝试摆脱 5 年以上的 PHP 开发并尝试 Ruby/Rails。我选择了使用 Rails 进行敏捷 Web 开发,并且一直在关注它。我携带的不同版本包括 Mac OS X Snow Leopard(最初已迁移到 Mountain Lion)和 Ruby/Rails 1.8.7/3.2.6。

将数量添加到购物车时,我的代码如下所示:cart.rb (model)

class Cart < ActiveRecord::Base
  has_many :line_items, :dependent => :destroy

  def add_product(product_id)
    current_item = line_items.find_by_product_id(product_id)
    if current_item
      current_item.quantity += 1
    else
      current_item = line_items.build(:product_id => product_id)
    end
    current_item
  end
end

我在 line_item.rb 模型和 line_items_controller.rb 中有 attr_accessible :quantity 我正在调用@line_item = current_cart.add_product(product.id)。代码在您第一次将产品添加到购物车时运行良好,但 Rails 第二次给我错误:

undefined method `+' for nil:NilClass

并指出问题中的明显线(加号上方)。有什么建议么?谢谢。

编辑:如果有人也可以在评论中推荐这是学习 Rails 的最佳途径,或者我应该拿起另一本书或使用另一个网站/等,因为这不是第一次代码出错了这本书。

编辑 2:摘录 line_items_controller.rb(第 40-56 行)

def create
  @cart = current_cart
  product = Product.find(params[:product_id])
  @line_items = @cart.add_product(product.id) #product.id, product didn't work.

  respond_to do |format|
    if @line_item.save
      format.html { redirect_to @line_item.cart, :notice => 'Line item was successfully created.' }
      format.json { render :json => @line_item, :status => :created, :location => @line_item }
    else
      format.html { render :action => "new" }
      format.json { render :json => @line_item.errors, :status => :unprocessable_entity }
    end
  end
end

此外,由于代码适用于一个项目,而不是同一项目的连续添加,我认为它与 .save 无关。

4

3 回答 3

2

你确定数量不是零。

尝试

if current_item && current_item.quantity.present? 

代替

if current_item
于 2012-07-30T16:39:14.367 回答
2

永远不要将attr_accessor(不要与attr_accessible)与由数据库列支持的属性一起使用:您正在将活动记录生成的访问器(它会返回列值,可能默认值为 1)替换为使用一个实例变量。该实例变量未设置,因此返回 nil

使用 Rails 进行敏捷 Web 开发的早期版本很好(我曾经拥有第一版),但我会确保您拥有最新版本 - 我认为它们现在已经排在第 4 或第 5 位。

于 2012-07-30T16:45:08.510 回答
0

错误的意思是你的current_item对象是nil. 您的find_by_product_id查询没有找到任何具有您作为参数传递的 id 的对象。
尝试检查控制器传递给模型的 id。

于 2012-07-30T16:36:16.163 回答