我想在我的控制器中添加几个实例变量,因为在多个动作的视图中需要有问题的变量。但是,以下示例无法正常工作。

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方法之类的过滤器的最佳时间?

有帮助吗?

解决方案

这些类型的事情应该在 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

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

before_filter :set_toppings, :only => [ :show_pizza_topping ]

希望这有帮助。

编辑:以下是有关过滤器的更多信息在ActionController

其他提示

那些不是实例变量,是吗?

class A
  @x = 5
  def f
    puts @x
  end
end

A.new.f
=> nil

您在类级别定义它,而不是在实例级别定义它。作为“theIV”指出,你需要在实例方法中分配它们。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top