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.

UPDATE: Apparently the add_to_cart method was removed in version 4 of the book.

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?

Jarek

I’m working with 3rd edition of the book (p7.0) and can’t find the add_to_card method as well. Instead I have add_product, but when I do:

@count = session[:counter] = 0
or

session[:counter] = 0
I get error:

NameError in StoreController#add_to_cart undefined local variable or method `session’ for # Cart:0xb6d9a894>

When I do:

@count = 0

the counter doesn’t reset. Any ideas?

UPDATE

When I finally put

session[:counter] = 0
in a correct file (store_controller.rb which is now obvious for me, lol) then it started to work.

On the other hand, I was looking for add_to_cart method in the index of the book and it’s not there. Why? This made me thinking it’s not in there at all!

I’m working on it too long and it’s definitely time take a break if I do such mistakes.

Ramon M.

I’m working with 4th Ed. What I did is a method in application_controller.rb:


  def reset_session_counter
    if not session[:counter].nil?
      session[:counter] = 0
    end
  end

And then a call from the line_items_controller.rb create’s method:


@line_item = @cart.line_items.build(:product => product)
...
    respond_to do |format|
      if @line_item.save
        *reset_session_counter*
        format.html { redirect_to(@line_item.cart, :notice => 'Line item was successfully created.') }
...