为什么我的控制器的实例变量在视图中不起作用(Rails)
我想向我的控制器添加几个实例变量,因为多个操作视图中都需要有问题的变量。但是,下面的示例并不像我预期的那样工作。
class ExampleController < ApplicationController
@var1 = "Cheese"
@var2 = "Tomato"
def show_pizza_topping
# What I want is the above instance vars from within the view here
end
def show_sandwich_filling
# What I want is the above instance vars from within the view here
end
end
据我了解,Rails 从控制器获取实例变量并使它们在视图中可用。如果我在操作方法中分配相同的变量,它工作得很好 - 但我不想这样做两次。为什么我的方法行不通?
(注意:这是一个有点垃圾的例子,但我希望它有意义)
编辑:我在这里找到了这个问题的答案:Ruby 实例变量何时设置?
编辑 2:什么时候是使用过滤器(例如 before_filter 和初始化方法)的最佳时间?
I would like to add a couple of instance variables to my controller, since the variables in question are required from within more than one action's view. However, the below example does not work as I would expect.
class ExampleController < ApplicationController
@var1 = "Cheese"
@var2 = "Tomato"
def show_pizza_topping
# What I want is the above instance vars from within the view here
end
def show_sandwich_filling
# What I want is the above instance vars from within the view here
end
end
As I understand it, Rails takes the instance variables from the controller and makes them available in the view. If I assign the same variables within the action methods, it works fine - but I don't want to do it twice. Why does my way not work?
(Note: this is a bit of a rubbish example, but I hope it makes sense)
EDIT: I have found the answer to this question here: When do Ruby instance variables get set?
EDIT 2: when is the best time to use filters such as before_filter and the initialize method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些类型的事情应该在
before_filter
中处理。顾名思义,before 过滤器是一种在任何操作之前或仅在您声明的操作之前调用的方法。一个例子:或者,您可以让 before_filter 仅对您的一项操作起作用
希望这会有所帮助。
编辑:以下是有关 ActionController 中的过滤器的更多信息< /a>.
These types of things should be handled in a
before_filter
. A before filter, like the name implies, is a method that will get called before any actions, or only the ones you declare. An example:Or, you could have your before_filter only work on one of your actions
Hope this helps.
EDIT: Here's some more information on filters in ActionController.
这些不是实例变量,是吗?
您在类级别而不是实例级别定义它。正如“theIV”指出的那样,您需要在实例方法内分配它们。
Those aren't instance variables, are they?
You're defining it at the class-level, not the instance-level. As "theIV" points out, you need to assign them inside an instance method.