控制器所有动作的相同实例变量 [英] 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(.:格式)))'
)
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屋!