Reset Cart after mark_cart_as_purchased

123 Views Asked by At

Basically i've been following the RailsCasts Paypal Basic tutorial and after a cart is marked as purchased, you need to reset session[:cart_id] = nil

Here's my code

class Customer::CartsController < ApplicationController
 def show
   @cart = if current_user
    current_user.cart
   else
    Cart.find session[:cart_id]
    Cart.destroy session[:cart_id]
    session[:cart_id] = nil if current_user.cart.purchased_at
   end
   if session[:cart_id].nil?
    @cart = Cart.create(session[:cart_id])
   end
   @cart
   end
end

I can't seem to figure out why its not working. I would appreciate any pointers as to where i've gone wrong. Thanks

UPDATE: i figured when the 'if current_user' is true, which is most of the time. The else block doesn't get rendered. So i updated it to

 class Customer::CartsController < ApplicationController
   def show
     @cart = if current_user
     current_user.cart ||= Cart.find session[:cart_id]
     session[:cart_id] = nil if current_user.cart.purchased_at
     end
     if session[:cart_id].nil?
      current_user.cart = Cart.create(params[:id])
      session[:cart_id] = current_user.cart.id
     end
     current_user.cart
  end

end

Still no luck! No idea, what i'm doing wrong now....

1

There are 1 best solutions below

4
aruanoc On

Hard to see without posting the actual error, but I see an issue in the line below:

current_user.cart = Cart.create(params[:id])

The function create takes a hash as the argument, so you would need to call it as shown below:

current_user.cart = Cart.create(:user_id => params[:id])

** Assuming that the id param is the user id.

Check the create function documentation.