【发布时间】:2011-04-15 18:31:50
【问题描述】:
您好,抱歉,如果这是一个愚蠢的问题,我真的是 ROR 世界的新手,我正在努力学习。
我正在阅读使用 Rails 电子书的敏捷 Web 开发,并按照本书程序进行操作,但出现此错误:
Line itemsController#create 中的 NoMethodError
当你没想到时,你有一个 nil 对象! 您可能期望有一个 Array 的实例。 评估 nil 时发生错误。
这是购物车模型
class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
def add_product(product_id)
current_item = line_items.where(:product_id => product_id).first
if current_item
current_item.quantity += 1
else
current_item = LineItem.new(:product_id => product_id)
line_items << current_item
end
current_item
end
end
这是行项目控制器正在调用哪个方法
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
respond_to do |format|
if @line_item.save
format.html { redirect_to(@line_item.cart, :notice => 'Line item was successfully created.') }
format.xml { render :xml => @line_item.cart, :status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => @line_item.errors, :status => :unprocessable_entity }
end
end
end
Rails 版本 3.0.5 Ruby 版本 1.8.7
有什么建议吗?你能看出有什么问题吗? 谢谢
【问题讨论】:
-
请张贴行号。
-
使用堆栈跟踪发布完整错误,您忽略了关键信息。
-
在您发布错误的行号之前,您不会获得任何有用的帮助。
标签: ruby-on-rails ruby ruby-on-rails-3