Matt Bettinson Matt Bettinson - 2 months ago 8
reST (reStructuredText) Question

Increment counter on page hit in Rails

I have this so far. I want to increment the counter every time a GET request is sent to counter#add. What am I doing wrong?

class CounterController < ApplicationController
def initialize
@counter = 0
end

def home
end

def add
@counter += 1
end
end

Answer

Every get request is a NEW instance of CounterController, so it's always starting at zero. This is why whenever you create an instance variable like @post it's not there on the next request. @counter is just another example of that.

An alternative might be to make it a class instance...

class CounterController < ApplicationController

  @counter = 0

  def self.add
    @counter += 1
  end

  def self.counter
    @counter
  end

  def home
  end

  def add
    class.add
  end

  def show_counter
    class.counter
  end

end
Comments