fenec
fenec

Reputation: 5806

rails: how do we call a variable that we can use in all the action that belongs to the same controller?

I would like to do something like using instance variables

def index
 @balance=1000
enb

def increment
 @balance+=1
end 

what kind of variable should i use?

Upvotes: 0

Views: 140

Answers (1)

Larry K
Larry K

Reputation: 49114

There are different ways to interpret your question, not sure which you meant:

All actions (in the same or different controllers) can use instance variables with the same name. But only 1 action is called per HTML request/response cycle.

If you want an instance variable to be set in one action and have the same value in another action (as part of a different request from the same web browser), use the Session store. Eg

def index
   @balance=1000
   # @balance can be used in views
   session[:balance] = @balance # now stored for the rest of the user's session
end

def increment
   @balance = session[:balance] # initialize
   @balance += 1
   session[:balance] = @balance # update
end 

####################################################

# a DRYer way is to use a filter to set the value
# Added, also we set the value to 0 if nil so it can later be added to.
# Remember that nil + 1 => error. 
before_filter :load_balance
def load_balance
  @balance = session[:balance] || BigDecimal.new('0') # use BigDecimal
                                                      # for money calculations
end

# the filter can be set per controller.

Upvotes: 1

Related Questions