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

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

问题描述

我有一个定义了两个动作的 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(.:格式)))')

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天全站免登陆