控制器的所有动作均具有相同的实例变量 [英] Same instance variable for all actions of a controller
问题描述
我有一个定义了两个动作的rails控制器:index
和show
.
我在index
操作中定义了一个实例变量.代码如下所示:
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
如何访问show.html.erb
模板中的@some_instance_variable
?
推荐答案
除非要通过index
操作渲染show.html.erb
,否则还需要在show操作中设置@some_instance_variable
.调用控制器动作时,它会调用匹配方法-因此,当使用show
动作时,不会调用index
方法的内容.
Unless you're rendering show.html.erb
from the index
action, you'll need to set @some_instance_variable
in the show action as well. When a controller action is invoked, it calls the matching method -- so the contents of your index
method will not be called when using the show
action.
如果在index
和show
动作中都需要将@some_instance_variable
设置为相同的内容,则正确的方法是定义由index
和show
调用的另一种方法来设置实例变量.
If you need @some_instance_variable
set to the same thing in both the index
and show
actions, the correct way would be to define another method, called by both index
and show
, that sets the instance variable.
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
方法设为私有可防止将其作为控制器操作调用
Making the set_up_instance_variable
method private prevents it from being called as a controller action if you have wildcard routes (i.e., match ':controller(/:action(/:id(.:format)))'
)
这篇关于控制器的所有动作均具有相同的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!