Ruby on Rails session[:counter ] increases by two

I am studying pragmatic bookshelf lessons. I try to make a session counter. my store controller is

  class StoreController < ApplicationController
  def increment_counter
  if session[:counter].nil?
    session[:counter] = 0
  end
  session[:counter] += 1
end
  def index
    @count = increment_counter
    @products  = Product.all
    @cart = current_cart
    @time = Time.now
    @shown_message = "You've been here #{@count} times" if increment_counter >5
  end
end

and my view is

<h5><p><%= @shown_message %></p></h5>..

until 5 times it does not work . but after it starts to count as 5,7,9,11. . what is wrong with my session[:counter]?

Answers


You call increment_counter twice in your action : first when setting @count, and then again in your condition for @shown_message.


In complement to ksol answer. Use @count in the last call.

def index
  @count = increment_counter
  @products  = Product.all
  @cart = current_cart
  @time = Time.now
  @shown_message = "You've been here #{@count} times" if @count >5
end

Need Your Help

Wordpress Ajax returns full html page from functions.php, not echo

php jquery ajax wordpress

I am using a wordpress ajax call to return simple content from a function in wordpress theme functions.php. However, a full html page is returned instead.

Spring SP Class generation with or without Eclipse

java sql database spring scripting

With Hibernate+Eclipse you can generate POJO classes that represent the tables. You can then wire it all together pretty easily with Spring. However, if you have to interact with stored procedures ...