0

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
Matt Bettinson
  • 533
  • 3
  • 8
  • 22

1 Answers1

1

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
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53
  • Thanks Steve! I followed your example and changed some things. – Matt Bettinson Sep 24 '16 at 18:33
  • In ruby @@variable_name is used for class variable and @variable_name is used for instance variable name. – Aditya Varma Sep 24 '16 at 19:39
  • @c0de222 except that every class is an instance of a superclass and can therefore have its own instance variables, referred to as class instance variables. This answer explains it well. http://stackoverflow.com/a/15773671/2516474 – SteveTurczyn Sep 24 '16 at 20:52