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.erbfrom theindexaction, you’ll need to set@some_instance_variablein the show action as well. When a controller action is invoked, it calls the matching method — so the contents of yourindexmethod will not be called when using theshowaction.If you need
@some_instance_variableset to the same thing in both theindexandshowactions, the correct way would be to define another method, called by bothindexandshow, that sets the instance variable.Making the
set_up_instance_variablemethod private prevents it from being called as a controller action if you have wildcard routes (i.e.,match ':controller(/:action(/:id(.:format)))')