我正在使用Agile Web Development with Rails(第4版)一书,并且遇到了一段不起作用的代码。我努力弄清楚它为什么不起作用,但我没有做到。LineItemsController中的NoMethodError#create
BACKGROUD信息
下列类别涉及:
class Cart < ActiveRecord::Base
has_many :line_items, :dependent => :destroy
end
class LineItem < ActiveRecord::Base
belongs_to :product
belongs_to :cart
end
class ApplicationController < ActionController::Base
protect_from_forgery
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
end
end
NOW 这里就是失败:
class LineItemsController < ApplicationController
def index
@line_items = LineItem.all`
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @line_items }
end
end
# GET /line_items/1
# GET /line_items/1.xml
def show
@line_item = LineItem.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @line_item }
end
end
# GET /line_items/new
# GET /line_items/new.xml
def new
@line_item = LineItem.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @line_item }
end
end
# GET /line_items/1/edit
def edit
@line_item = LineItem.find(params[:id])
end
# POST /line_items
# POST /line_items.xml
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = **@cart.line_items.build(:product => product)**`
错误信息 * NoMethodError在LineItemsController#创建 未定义的方法OD`line_items' 9:Fixnum对象 Rails.root:/家庭/ tmiskiew /仓库*
*应用程序/控制器/ line_items_controller.rb:53:在`创建” 请求 参数: { “PRODUCT_ID”= > “4”, “authenticity_token”=> “dR4nL5zI + R7qIIPwNkl3EoaI1KyFWRokvh92m3PwD8o =”} *
任何一个想法有什么不对@ cart.line_items.build? 我的工作轨道3.0.9和1.8.7的红宝石
感谢 托马斯
你的意思是我必须完成current_cart的其他分支返回会议?我试过了,但现在我正在获取SQLite3 :: BusyException:数据库被锁定:INSERT INTO“carts”(“updated_at”,“created_at”)VALUES('2011-08-04 07:51:23.552125','2011 -08-04 07:51:23.552125' ) – Thomas
返回会议,而不是车,是因为下面的代码是: '的respond_to做|格式| if line_item.save format.html {redirect_to(@ line_item.cart, :notice =>'订单项成功创建')} format.xml {render:xml => @line_item, :status = >:created,:location => @line_item} else format.html {render:action =>“new”} format.xml {render:xml => @ line_item.errors, :status =>:unprocessable_entity} 结束 end' – Thomas
您可以返回'cart',并且可以使用你把会话[:cart_id]这样的'@cart = current_cart'和调用'@ cart.id',这会给你会喜欢的精确值[:cart_id](毕竟你放在会话cart.id) – cristian