Почему переменные экземпляра моего контроллера не работают в представлениях (направляющие)

Другая попытка:

тираннозавр рекс: Большая Ящерица

6
задан Community 23 May 2017 в 10:27
поделиться

2 ответа

These types of things should be handled in a before_filter. A before filter, like the name implies, is a method that will get called before any actions, or only the ones you declare. An example:

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

Or, you could have your before_filter only work on one of your actions

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

Hope this helps.

EDIT: Here's some more information on filters in ActionController.

10
ответ дан 9 December 2019 в 20:46
поделиться

Those aren't instance variables, are they?

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

A.new.f
=> nil

You're defining it at the class-level, not the instance-level. As "theIV" points out, you need to assign them inside an instance method.

2
ответ дан 9 December 2019 в 20:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: