Rails Agile Web Development 4th, Page120

匿名 · 2012年08月27日 · 最后由 nuclearkitten 回复于 2012年08月27日 · 2653 次阅读

line_items_controller.rb def create @cart = current_cart product = Product.find(params[:product_id]) @line_item = @cart.line_items.build(product_id: product.id)

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

carts_controller.rb

def show @cart = Cart.find(params[:id])

respond_to do |format| format.html # show.html.erb format.json { render json: @cart } end end app/views/carts/show.html.erb

<%= notice %>

Your programatic Cart

<%= link_to 'Edit', edit_cart_path(@cart) %> | <%= link_to 'Back', carts_path %>

<%= button_to 'Add to Cart', line_items_path(product_id: product) %>

问题: button_to 到 line_items#create,然后 redirect_to "carts#show" 最后到 show.html.erb

出错:undefined method `title' for nil:NilClass

说明 item.product 是一个 nil?

这是什么情况,怎么显示不完整

你是用的 Agile Web Development with Rails3.2 吗?错误的提示应该有定位,把出错的那行贴出来

匿名 #4 2012年08月27日

#3 楼 @w7938940 是的,我自己弄好了,修改很多地方

匿名 #5 2012年08月27日

#3 楼 @w7938940 我感觉书上的也对,但不知道为什么就出错了?

匿名 #6 2012年08月27日

<%= item.product.title %> #5 楼 @nuclearkitten 错误提示,就是这一行,item.product 为 nil,

需要 登录 后方可回复, 如果你还没有账号请 注册新账号