Same instance variable for all actions of a controller Same instance variable for all actions of a controller ruby ruby

Same instance variable for all actions of a controller


You can define instance variables for multiple actions by using a before filter, e.g.:

class FooController < ApplicationController  before_filter :common_content, :only => [:index, :show]  def common_content    @some_instance_variable = :foo  endend

Now @some_instance_variable will be accessible from all templates (including partials) rendered from the index or show actions.


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_variableenddef show  set_up_instance_variableendprivatedef set_up_instance_variable  @some_instance_variable = fooend

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)))')