byCoder
byCoder

Reputation: 9184

Rails create cart on session when user go to webpage

I need to do shoping cart, but why when i first go to page, i didn't see @cart object, but if refresh, all is ok. If simple say: cart is created not on first page load, but on second, and this is bad.... How to do, that when i open in browser url of page, i imidiatly see cart object?

My code: (app_controller)

  before_filter :current_cart 
private
    def current_cart
      Cart.find(session[:cart_id])
      @cart = Cart.find(session[:cart_id])
      rescue ActiveRecord::RecordNotFound
      cart = Cart.create
      session[:cart_id] = cart.id
      cart
    end

And view:

%li
              = link_to "Перейти в корзину", @cart

But how to create cart object when page is open.... not when i am on page, an done something....

Upvotes: 0

Views: 907

Answers (2)

MBO
MBO

Reputation: 30985

To put it simple - in rescue block (when cart is not yet in database) you need to assign newly created cart to instance variable @cart, not local variable cart.

before_filter :current_cart 

private

def current_cart
  @cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
  @cart = Cart.create
  session[:cart_id] = @cart.id
  @cart
end

Upvotes: 1

Huy
Huy

Reputation: 11206

Try this:

 before_filter :current_cart 
private
    def current_cart
      @cart = Cart.where(id: session[:cart_id]).first #this will return nil if the Cart with id session[:cart_id] does not exist
      @cart = Cart.create if @cart.nil?
      session[:cart_id] = @cart.id
      @cart
    end

Upvotes: 1

Related Questions