我将我的购物车存储在数据库中,并current_cart
在我的应用程序助手中有一个方法。
private
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
每个购物车都有_many line_items。当客户准备结账时,他们会被发送到order/new
……当订单从支付网关成功返回时,一切都很好。但是我正在测试订单失败,我的控制器似乎有问题create
,因为@order
对象没有被保存,并且 rails 正在尝试order#new
再次渲染。它甚至没有尝试查看付款是否成功。我不确定出什么问题,因为几天前我测试它时它正在工作。
def create
@order = current_cart.build_order(params[:order])
@order.ip_address = request.remote_ip
@order.total_tokens = @order.calculate_total_tokens
@order.user_id = current_user
if @order.save
if @order.purchase
render :action => "success"
else
render :action => "failure"
end
else
render :action => "new"
end
end
def new
@cart = current_cart
if @cart.line_items.empty?
redirect_to store_url, :notice => "Your cart is empty."
return
end
@order = Order.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @order }
end
end
当它尝试呈现页面时出现此错误,显然是因为尚未保存订单:
NoMethodError in Orders#create
Showing /Users/justin/Code/trackable/app/views/orders/_order_cart.html.erb where line #1 raised:
undefined method `line_items' for nil:NilClass
Extracted source (around line #1):
1: <% unless @cart.line_items.empty? %>
2: <div id="checkout_cart">
3: <% @cart.line_items.each do |l| %>
4: <%= l.quantity %>
不知道发生了什么