Variables visible in all actions in a controller

Hello,

I want make a variable visible to all actions in a controller. Everytime user submits a parameter “school_class_id” on the basis of which I assign a variable which I want to make available to all the actions in controller.

I used before_filter: set_class_id where set_class_id is defined as

def set_class_id

@currentClassid = session[:currentclassid]

if !params[:class_list].nil?

if !params[:class_list][:class_id].nil?

@currentClassid = params[:class_list][:class_id]

end

end

end

In this case, value of @currentClassid changes in index action. However in other actions, it remains the same as the value it is assigned intially for the first time ( In this case , the value in the session ). I am clueless why this is happening. If in index action, the value of @currentClassid is changing, then why not in other actions?

Jaikishan Jalan wrote:

Hello,
I want make a variable visible to all actions in a controller. Everytime
user submits a parameter "school_class_id" on the basis of which I assign a
variable which I want to make available to all the actions in controller.

I used before_filter: set_class_id where set_class_id is defined as

def set_class_id
   @currentClassid = session[:currentclassid]
   if !params[:class_list].nil?
      if !params[:class_list][:class_id].nil?
            @currentClassid = params[:class_list][:class_id]
     end
end
end

In this case, value of @currentClassid changes in index action. However in
other actions, it remains the same as the value it is assigned intially for
the first time ( In this case , the value in the session ). I am clueless
why this is happening. If in index action, the value of @currentClassid is
changing, then why not in other actions?

How could it change? Instance variables (by definition) are restricted
to an instance of a class. When you view another action the filter
runs again and @currentClassid is set to session[:currentclassid]. If
you do want it to persist across actions you could put in back in the
session after setting it.

If that filter runs in all actions, and the params are received, the
instance variable should store what's in params. I guess in actions
other than index the params are not being sent.

A note on conventions: in Ruby instance variables use snake case:
@current_class_id.