imr*_*ran 12 ruby scope ruby-on-rails instance-variables
我有一个rails控制器,定义了两个动作:index和show.我在index操作中定义了一个实例变量.代码如下所示:
def index
  @some_instance_variable = foo
end
def show
  # some code
end
我如何可以访问@some_instance_variable的show.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
现在@some_instance_variable可以从index或show动作渲染的所有模板(包括部分)访问.
Emi*_*ily 13
除非您show.html.erb从index动作渲染,否则您还需要设置@some_instance_variableshow动作.调用控制器操作时,它会调用匹配方法 - 因此index在使用show操作时不会调用方法的内容.
如果您需要@some_instance_variable在两个设置为相同的事情index和show行为,正确的方法是定义的另一种方法,通过这两个所谓的index和show,即设置实例变量.
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
set_up_instance_variable如果您具有通配符路由,则将该方法设为私有可防止将其作为控制器操作调用(即match ':controller(/:action(/:id(.:format)))')