控制器的所有操作具有相同的实例变量
我有一个 Rails 控制器,定义了两个操作:index
和 show
。 我在 index
操作中定义了一个实例变量。代码如下:
def index
@some_instance_variable = foo
end
def show
# some code
end
How can I access the @some_instance_variable
in show.html.erb
template?
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
How can I access the @some_instance_variable
in show.html.erb
template?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 before 过滤器为多个操作定义实例变量,例如:
现在可以从
index
或渲染的所有模板(包括部分模板)访问
操作。@some_instance_variable
>显示You can define instance variables for multiple actions by using a before filter, e.g.:
Now
@some_instance_variable
will be accessible from all templates (including partials) rendered from theindex
orshow
actions.除非您从
index
操作渲染show.html.erb
,否则您还需要在 show 操作中设置@some_instance_variable
。当调用控制器操作时,它会调用匹配的方法 - 因此在使用show
操作时不会调用index
方法的内容。如果您需要在
index
和show
操作中将@some_instance_variable
设置为相同的内容,正确的方法是定义另一个方法,称为通过index
和show
设置实例变量。如果您有通配符路由(即
match ':controller(/:action(/:id(.:format))),则将
)set_up_instance_variable
方法设为私有可防止将其作为控制器操作调用)'Unless you're rendering
show.html.erb
from theindex
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 yourindex
method will not be called when using theshow
action.If you need
@some_instance_variable
set to the same thing in both theindex
andshow
actions, the correct way would be to define another method, called by bothindex
andshow
, that sets the 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)))'
)