Simply reset the count in the session


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

Tim

I’m working with the 4th edition. I don’t see this add_to_cart method anywhere. What I did is add

session[:counter] = 0
to the create method in the line_items_controller.rb file.

This seems to work, but is there a better or more intuitive way of of doing it?

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?