Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same instance variable for all actions of a controller

I have a rails controller with two actions defined: index and show. I have an instance variable defined in index action. The code is something like below:

def index
  @some_instance_variable = foo
end

def show
  # some code
end

How can I access the @some_instance_variable in show.html.erb template?

like image 838
imran Avatar asked Feb 17 '12 15:02

imran


People also ask

Can an object have more than one instance variable?

All instances of an object have their own copies of instance variables, even if the value is the same from one object to another. One object instance can change values of its instance variables without affecting all other instances.

Is instance variable same as object?

Memory allocated for the member of class at run time is called object or object is the instance of Class. Memory allocated For Any at run time is called as instance variable.

What is an instance variable give an example?

Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class. Instance variables can be declared at the class level before or after use. Access modifiers can be given for instance variables.

What does an instance variable declaration consist of multiple options?

Instance Variables An instance variable declaration consists of the following parts: access specifier (private) type of variable (such as int) name of variable (such as value)


1 Answers

Unless you're rendering show.html.erb from the index action, you'll need to set @some_instance_variable in the show action as well. When a controller action is invoked, it calls the matching method -- so the contents of your index method will not be called when using the show action.

If you need @some_instance_variable set to the same thing in both the index and show actions, the correct way would be to define another method, called by both index and show, that sets the instance variable.

def index
  set_up_instance_variable
end

def show
  set_up_instance_variable
end

private

def set_up_instance_variable
  @some_instance_variable = foo
end

Making the set_up_instance_variable method private prevents it from being called as a controller action if you have wildcard routes (i.e., match ':controller(/:action(/:id(.:format)))')

like image 142
Emily Avatar answered Nov 24 '22 16:11

Emily