控制器的所有动作均具有相同的实例变量 [英] Same instance variable for all actions of a controller

查看:86
本文介绍了控制器的所有动作均具有相同的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个定义了两个动作的rails控制器:indexshow. 我在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.

如果在indexshow动作中都需要将@some_instance_variable设置为相同的内容,则正确的方法是定义由indexshow调用的另一种方法来设置实例变量.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆