【发布时间】:2011-08-04 07:08:11
【问题描述】:
我正在使用 Rails 的敏捷 Web 开发(第 4 版)一书,但遇到了一段无法正常工作的代码。我努力想弄清楚为什么它不起作用,但我没有成功。
背景信息
涉及以下类:
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
现在 这是失败的地方:
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)**`
错误信息 *LineItemsController 中的 NoMethodError#create 9:Fixnum 的未定义方法“line_items” Rails.root: /home/tmiskiew/depot*
*app/controllers/line_items_controller.rb:53:in `create' 要求 参数: {"product_id"=>"4", "authenticity_token"=>"dR4nL5zI+R7qIIPwNkl3EoaI1KyFWRokvh92m3PwD8o="}*
有人知道@cart.line_items.build 有什么问题吗? 我正在使用 rails 3.0.9 和 ruby 1.8.7
谢谢 托马斯
【问题讨论】:
标签: ruby-on-rails-3