每次我尝试渲染来自不同视图的东西时,我都会得到一个NoMethodError:undefined方法`每个'为零: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 %>
但是,当我自己加载该页面视图时,我没有错误。 有人能帮助我吗?
答案 0 :(得分:0)
您的模板 guitar_sounds / index 需要定义@guitar_sounds
,并能够迭代其项目。
如果您重复使用模板而未向@guitar_sounds
分配任何值,则默认情况下它将为nil
,因此您可以看到错误。
希望它澄清一点问题!
答案 1 :(得分:0)
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文档:Passing Local Variables to partials/templates。
答案 2 :(得分:0)
加载部分不会自动命中控制器方法。通过这种方式,听起来唯一正在运行的控制器方法是@guitar_sounds
,但guitar_sounds#index
变量正在@guitar_sounds
中定义。我只是在UploadsController
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