订单完成后的新购物车
我有一个电子商务解决方案,当订单完成时,我希望用户能够去购物车看到它是空的。 以前我摧毁了购物车,但不建议这样做,因为根据一些建议我添加了一个列到购物车
:active, :boolean, :default true
我的推车控制器看起来像这样
def show @cart = Cart.find_by_id(session[:cart_id]) end # GET /carts/new def new @cart = Cart.create session[:cart_id] = @cart.id @cart redirect_to @cart end
我的应用程序控制器中有一个方法,用于创建购物车。
def current_cart Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound cart = Cart.create session[:cart_id] = cart.id cart end
在订单完成后,我将:active列从true更改为false。 我怎么能这样做,如果current_cart.active? 是假的,它创造了一个新车?
我试过了
def current_cart if Cart.find(session[:cart_id]).active? ==false cart = Cart.create session[:cart_id] = cart.id end rescue ActiveRecord::RecordNotFound cart = Cart.create session[:cart_id] = cart.id cart end
但我好像有两辆车一次工作..
更新
试着
def current_cart if Cart.find(session[:cart_id]).active? ==false reset_session else Cart.find(session[:cart_id]) end
徒劳无功..
如果Cart.find
返回的Cart.find
未激活,您尝试的代码不会返回Cart
对象 – 它返回cart.id
最简单的解决方法是返回创建的购物车(就像你在rescue
条款中所做的那样):
def current_cart cart = Cart.find(session[:cart_id]) unless cart.active? cart = Cart.create session[:cart_id] = cart.id end cart rescue ActiveRecord::RecordNotFound cart = Cart.create session[:cart_id] = cart.id cart end
你也应该干它 – 类似于:
def current_cart begin cart = Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound cart = nil end unless cart && cart.active? cart = Cart.create session[:cart_id] = cart.id end cart end
如果您不想在新方案中实际创建购物车,请使用new
而不是create
:
def current_cart cart = Cart.find(session[:cart_id]) unless cart.active? cart = Cart.new end cart rescue ActiveRecord::RecordNotFound cart = Cart.create session[:cart_id] = cart.id cart end