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

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

 def index @some_instance_variable = foo end def show # some code end 

如何访问show.html.erb模板中的show.html.erb

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

如果你需要在indexshow动作@some_instance_variable设置为相同的东西,那么正确的方法是定义另一个方法,由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 

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

您可以使用beforefilter为多个操作定义实例变量,例如:

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

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