从不同视图呈现时,nil:NilClass 的未定义方法 'each'



每次我尝试渲染从不同的视图定位的东西,我得到一个NoMethodError:未定义的方法' each'为nil:NilClass。当我将以下代码放入我想要渲染的视图中时,就会发生这种情况:

视图/上传/myuploads.html.erb

<%= render template: 'guitar_sounds/index' %>

它告诉我错误似乎在模板所在的特定代码块中:

视图/guitar_sounds index.html.erb

    <% @guitar_sounds.each do |sound| %> <!-- Error here -->
           <%= render "guitar_sound", sound:sound %>
    <% end %>

但是,当我自己加载该页面视图时,我没有得到任何错误。有人能帮帮我吗?

加载分部不会自动命中控制器方法。这样,听起来唯一正在运行的控制器方法是uploads#myuploads,但您的@guitar_sounds变量在guitar_sounds#index中定义。我只需在UploadsController

中定义@guitar_sounds变量
UploadsController < ApplicationController
  def myuploads
    # here is where @guitar_sounds needs to be defined
    @guitar_sounds = GuitarSound.all
  end
end

假设你在很多方法中都需要@guitar_sounds,你可以在before_action

中定义它
UploadsController < ApplicationController
  before_action :set_guitar_sounds
  def myuploads
    # normal controller code
  end
  private
  def set_guitar_sounds
    @guitar_sounds = GuitarSound.all
  end
end
现在@guitar_sounds将为UploadsController
中的每个方法设置

您的模板guitar_sounds/index期望定义@guitar_sounds,并且能够遍历其项。

如果您重用模板而没有为@guitar_sounds赋值,默认情况下它将是nil,因此您可以看到错误。

希望它能澄清一点问题!

guitar_sounds/index期望@guitar_sounds被定义,也就是说,不是nil,所以它可以遍历它的项。

你应该使用局部变量。

<%= render template: 'guitar_sounds/index', guitar_sounds: @guitar_sounds %> #or other @ variable

和在你的视图:

<% guitar_sounds.each do |sound| %> 
       <%= render "guitar_sound", sound:sound %>
<% end %>

现在guitar_sounds(注意缺少@)是一个传递给渲染函数的局部变量!

编辑:查看rails文档:将局部变量传递给局部/模板

相关内容

最新更新