控制器的所有操作的相同实例变量

imr*_*ran 12 ruby scope ruby-on-rails instance-variables

我有一个rails控制器,定义了两个动作:indexshow.我在index操作中定义了一个实例变量.代码如下所示:

def index
  @some_instance_variable = foo
end

def show
  # some code
end
Run Code Online (Sandbox Code Playgroud)

我如何可以访问@some_instance_variableshow.html.erb模板?

Mor*_*ori 57

您可以使用before过滤器为多个操作定义实例变量,例如:

class FooController < ApplicationController
  before_filter :common_content, :only => [:index, :show]

  def common_content
    @some_instance_variable = :foo
  end
end
Run Code Online (Sandbox Code Playgroud)

现在@some_instance_variable可以从indexshow动作渲染的所有模板(包括部分)访问.

  • 这是一个更好的答案! (4认同)
  • 仅供未来读者使用.弃用警告:不推荐使用before_filter,将在Rails 5.1中删除.请改用before_action. (2认同)

Emi*_*ily 13

除非您show.html.erbindex动作渲染,否则您还需要设置@some_instance_variableshow动作.调用控制器操作时,它会调用匹配方法 - 因此index在使用show操作时不会调用方法的内容.

如果您需要@some_instance_variable在两个设置为相同的事情indexshow行为,正确的方法是定义的另一种方法,通过这两个所谓的indexshow,即设置实例变量.

def index
  set_up_instance_variable
end

def show
  set_up_instance_variable
end

private

def set_up_instance_variable
  @some_instance_variable = foo
end
Run Code Online (Sandbox Code Playgroud)

set_up_instance_variable如果您具有通配符路由,则将该方法设为私有可防止将其作为控制器操作调用(即match ':controller(/:action(/:id(.:format)))')

  • 只需向控制器添加`before_action:set_up_instance_variable,only:[:show,:index]`.在您指定的任何操作之前,它将运行`set_up_instance_variable`. (2认同)