6

我想向我的控制器添加几个实例变量,因为有问题的变量需要在多个操作的视图中。然而,下面的例子并没有像我预期的那样工作。

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 方法)的最佳时间?

4

2 回答 2

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

或者,您可以让 before_filter 仅对您的一项操作起作用

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

希望这可以帮助。

编辑:这是有关ActionController中过滤器的更多信息。

于 2009-09-11T18:53:13.803 回答
2

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

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

A.new.f
=> nil

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

于 2009-09-11T18:55:07.313 回答