def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
debug 模式,都不进入 cart = Cart.create 但是如果去掉 ActiveRecord::RecordNotFound,会执行 rescue 后的语句,这是什么原因
正常来说 Cart.find(session[:cart_id])
是按 id find, 找不到就应该会抛出 ActiveRecord::RecordNotFound
#2 楼 @lyfi2003 抛出的异常是:ArgumentError (wrong number of arguments (0 for 1)): 很奇怪
ArgumentError (wrong number of arguments (0 for 1)):
app/models/cart.rb:2:in `<class:Cart>'
app/models/cart.rb:1:in `<top (required)>'
app/controllers/application_controller.rb:7:in `current_cart'
app/controllers/line_items_controller.rb:43:in `create'
car.rb 中
lass Cart < ActiveRecord::Base
has_many :line_items, :dependent => destroy
# attr_accessible :title, :body
end
Cart.find(session[:cart_id])
这里的 session[:cart_id] 是 nil,所以抛这个异常了 ArgumentError (wrong number of arguments (0 for 1)):
has_many :line_items, :dependent => destroy
destroy 加冒号
has_many :line_items, :dependent => :destroy