rails 中 nil:NilClass 的未定义方法“each”,同时在应用程序控制器中使用渲染不同控制器的动作

undefined method `each' for nil:NilClass in rails while using render a action of different controller in application controller

我生成脚手架名称作为页眉和页脚。 在 application.html.erb 我使用这个代码

<%= render template:"headers/index"  %>
<%= yield %>
<%= render template:"headers/index"  %>

用于渲染操作。这都是因为我想通过 html_safe 方法动态自定义页眉和页脚布局。

我遇到错误:

undefined method `each' for nil:NilClass

我知道为什么在另一个控制器中渲染动作时会出现此错误以及如何解决。但是仍然面临这个错误只是因为无法在我的 applications_controller.rb

中为 application.rb 中的 application.html.erb 定义一个动作
before_filter :set_headers
def set_headers
  @headers = Header.all
end

如何解决这个问题?

试试这个

before_filter :set_headers
def set_headers
 @headers ||= Header.all
end

改进你的代码