为什么我的控制器的实例变量在视图中不起作用(Rails)

Mar*_*ing 6 ruby scope ruby-on-rails instance-variables

我想在我的控制器中添加几个实例变量,因为在多个动作的视图中需要有问题的变量.但是,下面的示例并不像我预期的那样有效.

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
Run Code Online (Sandbox Code Playgroud)

据我了解,Rails从控制器获取实例变量并使其在视图中可用.如果我在动作方法中分配相同的变量,它工作正常 - 但我不想做两次.为什么我的方式不起作用?

(注意:这是一个垃圾的例子,但我希望它有意义)

编辑:我在这里找到了这个问题的答案:什么时候Ruby实例变量设置?

编辑2:何时是使用诸如before_filter和initialize方法之类的过滤器的最佳时间?

the*_*eIV 10

这些类型的东西应该在一个处理before_filter.前面的过滤器,如名称所示,是一种在任何操作之前调用的方法,或者只是您声明的操作.一个例子:

class ExampleController < ApplicationController

  before_filter :set_toppings

  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

protected

  def set_toppings
    @var1 = "Cheese"
    @var2 = "Tomato"
  end

end
Run Code Online (Sandbox Code Playgroud)

或者,您可以让您的before_filter仅适用于您的某个操作

before_filter :set_toppings, :only => [ :show_pizza_topping ]
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

编辑:这里有一些关于ActionController中过滤器的更多信息.