【发布时间】:2026-01-05 00:30:01
【问题描述】:
我想向我的控制器添加几个实例变量,因为有问题的变量需要从多个操作的视图中获取。然而,下面的例子并没有像我预期的那样工作。
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 从控制器中获取实例变量并使其在视图中可用。如果我在操作方法中分配相同的变量,它工作正常 - 但我不想做两次。为什么我的方法行不通?
(注意:这是一个有点垃圾的例子,但我希望它有意义)
编辑:我在这里找到了这个问题的答案:When do Ruby instance variables get set?
编辑 2:什么时候是使用过滤器(例如 before_filter 和 initialize 方法)的最佳时间?
【问题讨论】:
标签: ruby-on-rails ruby scope instance-variables