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?
Unless you're rendering
show.html.erb
from theindex
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 yourindex
method will not be called when using theshow
action.If you need
@some_instance_variable
set to the same thing in both theindex
andshow
actions, the correct way would be to define another method, called by bothindex
andshow
, that sets the instance variable.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)))'
)You can define instance variables for multiple actions by using a before filter, e.g.:
Now
@some_instance_variable
will be accessible from all templates (including partials) rendered from theindex
orshow
actions.