Same instance variable for all actions of a controller

imran picture imran · Feb 17, 2012 · Viewed 9.3k times · Source

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?

Answer

Mori picture Mori · Feb 17, 2012

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
  end
end

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