在我的 Rails 应用程序中,我有两个模型,一个 ClientPage
和一个 ContentSection
,其中 ClientPage has_many :content_sections
。我正在使用 nested_form
gem 来使用相同的表单编辑两个模型。只要 ClientPage
至少有一个 ContentSection
,这种方法就可以正常工作,但如果没有关联的 ClientSections
,则使用 nested_form
的 link_to_add
方法抛出以下 NoMethodError
:
undefined method `values_at' for nil:NilClass
该表格的结构如下:
<%= nested_form_for page, form_options do |f| %>
# ClientPage fields
# ClientSections
<%= f.link_to_add "Add new section", :content_sections %>
<% end %>
只要至少有一个 ClientSection
与该页面关联,就可以正常工作。一旦不存在,就会抛出错误。删除 link_to_add
也会阻止抛出错误。 (实际上 ContentSection
下有第二个嵌套模型,如果没有关联的模型,也会出现同样的问题。)
不确定我遗漏了什么相当明显的东西,但任何指示或建议将不胜感激。
最佳答案
终于解决了这个问题——错误是由于我以一种稍微不标准的方式使用 gem 造成的。在表单中,不是以标准方式呈现所有内容部分:
<%= f.fields_for :content_sections do |section_form| %>
# section fields
<% end %>
我把它放在一个循环中,因为我需要每个项目的索引(不存储在模型本身中):
<% page.content_sections.each_with_index do |section, index| %>
<%= f.fields_for :content_sections, section do |section_form| %>
# section fields
<% end %>
<% end %>
这样做的问题是,如果关联为空,则不会调用 fields_for
方法,因此 gem 无法构建对象的蓝图(用于添加调用 link_to_add
时的额外项目)。
解决方案是确保即使关联为空,也会调用 fields_for
:
<% if page.content_sections.empty? %>
<%= f.fields_for :content_sections do |section_form| %>
# section fields
<% end %>
<% end %>
关于ruby-on-rails-3 - 使用带有空关联的nested_form gem 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17609526/