Task C: Cart Creation #3

Simply reset the count in the session

def add_to_cart
  # ...
  session[:counter] = 0
end

Mark0

But what if the counter is not initialized? (like if someone pastes an add_to_cart url directly into the addressbar) Uh, then it is now initialized by the assignment.

Marcello:

Mark0 You could make a method for checking if the counter exists, initializing it in case it isn't there.

If it's there you could increment the count. On the add_to_cart method, then you can set it to 0 without trouble.

Aureliano:

I did something like:

  session[:counter] = nil

Why would the session be different than when the page was never loaded?

Russ:

If the session is not initialized, won't it be initialized by the assignment? yes

Eric:

If you want to display @count in store.rhtml you have to write:

def add_to_cart
  # ...
  @count = session[:counter] = 0
end

Zipper:

I think the easiest way is the first one, it is no need to check whether the session is existed.

def add_to_cart
  # ...
  session[:counter] = 0
end

Snowwolf:

Oops! It's strange that when I change the code

  @count = session[:counter] = 0

to
  @count = 0

It doesn't display any count number on my cart page.
Can anyone explain it to me?

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License