控制器的所有操作的相同实例变量
我有一个rails控制器,定义了两个动作: index
和show
。 我有一个在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
方法的内容。
如果你需要在index
和show
动作@some_instance_variable
设置为相同的东西,那么正确的方法是定义另一个方法,由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
如果您有通配符路由(即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
现在可以从index
或show
动作呈现的所有模板(包括部分)访问@some_instance_variable
。