Ruby on rails 在Nav内的轨道中放置全局变量的位置

Ruby on rails 在Nav内的轨道中放置全局变量的位置,ruby-on-rails,global-variables,Ruby On Rails,Global Variables,在我的导航栏中,我有一个变量,可能是@categories=Category.all。导航中有一个下拉列表,列出了类别 我想知道我把它放在哪里,因为它是布局的变量,而不是页面的变量。我想把它放在一个控制器里,但那不起作用 这是否适用于应用程序帮助程序?因为您需要在布局中显示它,我假设您在整个应用程序中都需要该布局,那么您所要做的就是: class ApplicationController < ActionController::Base before_action :set_cate

在我的导航栏中,我有一个变量,可能是
@categories=Category.all
。导航中有一个下拉列表,列出了类别

我想知道我把它放在哪里,因为它是布局的变量,而不是页面的变量。我想把它放在一个控制器里,但那不起作用


这是否适用于应用程序帮助程序?

因为您需要在布局中显示它,我假设您在整个应用程序中都需要该布局,那么您所要做的就是:

class ApplicationController < ActionController::Base
  before_action :set_categories  ## Set a before_action

  ## ...

  def set_categories
    @categories = Category.all
  end
end 
class ApplicationController

这样,由于您在
ApplicationController
级别的
操作之前定义了
set\u categories
方法将针对整个应用程序中的每个操作执行。

因为您需要在整个应用程序中所需的布局中的
导航栏中显示它,那么你所要做的就是:

class ApplicationController < ActionController::Base
  before_action :set_categories  ## Set a before_action

  ## ...

  def set_categories
    @categories = Category.all
  end
end 
class ApplicationController
这样,由于您在
ApplicationController
级别定义了一个
before\u action
set\u categories
方法将针对整个应用程序中的每个操作执行