[英]Undefined method each for nil:NilClass in erb template
我正在尝试遍历和数组,并检查以确保将其正确传递到模板,但遇到错误。
模板:
<% if defined?(source[:blacklist]) %>
"blacklist": [
<% source[:blacklist].each do |listed| %>
"<%= listed %>"
<% end %>
],
<% end %>
无循环时source [:blacklist]的输出:
"[\"/var/log/httpd/access.log*\", \"/var/log/httpd/error.log*\", \"/var/log/httpd/ssl_request_log\", \"/var/log/httpd/access_log\", \"/var/log/httpd/error_log\"]"
错误:
undefined method `each' for nil:NilClass
您的数组不存在,如果确实是一个字符串。
使用defined?(source[:blacklist])
带来问题,因为如果它不是数组(例如,已defined? nil
defined?(source[:blacklist])
,它将返回true defined? nil
defined? nil
是"nil"
,这是事实。
如果您无法更改数据的生成方式,请将其解析为Ruby数组,如果有意外数据或根本没有,则默认为空数组。
blacklist = source[:blacklist].gsub(/(\\[\\"|\\"\\])/, '').split('", "') || []
<% if not blacklist.empty? %>
如果source[:blacklist]
为nil,那么defined? source[:blacklist]
defined? source[:blacklist]
将返回字符串“ method”,即“ truthy”。
因此,它将失败,并且您将看到错误。... Undefined method each for nil:NilClass
当您说“无循环的源输出” ...是在控制器中还是在erb文件中检查了输出? 可能是该值未传递到erb,并且您通常希望使用实例变量将数据传递到html.erb文件。
另外,您应该注意,为source[:blacklist]
显示的输出实际上是一个字符串,而不是数组,因此即使传递了它,您仍然会在each
方法上收到错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.