Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

ruby on rails - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...