我想向我的控制器添加几个实例变量,因为有问题的变量需要在多个操作的视图中。然而,下面的例子并没有像我预期的那样工作。
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 和 initialize 方法)的最佳时间?