'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]?



Solution 1:[1]

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

Solution 2:[2]

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

Solution 3:[3]

In your store_controller.rb better code like that:

before_action :session_counter

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

  session[:counter] += 1
  @session_counter = session[:counter]
end

In store.html.erb like that:

<p>
  <% if @counter>5 %>
    <%= "U have visit the store #{@session_counter}  times!" %>
  <% end %>
</p>

looks a pretty nice and works easy.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ksol
Solution 2 fool-dev
Solution 3