我试图在页面中的多个部分使用表单部分。第一次,我通过"部分:" o"",第二次我通过"部分:" s& #34;"
当我传递第一个变量时它成功运行,但是第二次渲染表单partial时,它会生成一个未定义的方法`humanize'为零:NilClass"错误。
以下是提供其他部分内容的表单示例:
<some form stuff here>
<%= render partial: "item_form", locals: {f: f, section: "o"} %>
<some form stuff here>
<%= render partial: "item_form", locals: {f: f, section: "s"} %>
这是_item_form.html.erb部分正在呈现的部分:
<% unless @item.paragraphs.empty? %>
<% @item.paragraphs.each do |paragraph| %>
<% field_type = "Paragraph" if paragraph.paragraph_type == "#{section}paragraph" %>
<% field_type = "Figure description" if paragraph.paragraph_type == "#{section}figure" %>
<% field_type = "Bullet" if paragraph.paragraph_type == "#{section}bullet" %>
<div class="form-group">
<%= f.label field_type, class: "col-sm-2 control-label" %>
我得到的错误突出显示f.label行(上例中的最后一行)并吐出错误&#34;未定义的方法`humanize&#39;为零:NilClass&#34;。
知道这里发生了什么吗?如果我删除第一个渲染,它仍然无法正常工作。如果我删除第一个渲染并将第二个部分更改为&#34; o&#34;而不是&#34; s&#34;然后它起作用。添加&#34; o&#34;以外的任何其他字母;对于该部分拧紧它。
答案 0 :(得分:1)
field_type仅在某些情况下定义,您可以在代码中看到:
<% field_type = "Paragraph" if paragraph.paragraph_type == "#{section}paragraph" %>
<% field_type = "Figure description" if paragraph.paragraph_type == "#{section}figure" %>
<% field_type = "Bullet" if paragraph.paragraph_type == "#{section}bullet" %>
你确定其中至少有一个是真的吗?
我的猜测是你有一个带有oparagraph,ofigure或obullet类型的段落,但没有类型sparagraph,sfigure或sbullet,所以最后你将会有一个nil field_type。
我不知道你应用程序背后的业务逻辑,但我建议定义一个标准案例(如果你可以,当然),然后在必要时更新它,如:
<% field_type = "Paragraph" %>
<% field_type = "Figure description" if paragraph.paragraph_type == "#{section}figure" %>
<% field_type = "Bullet" if paragraph.paragraph_type == "#{section}bullet" %>
我还建议将此逻辑移动到帮助程序,而不是在视图本身中确定字段标签名称。