Zai*_*uch 4 nested-forms ruby-on-rails-3
在我的rails应用程序中,我有两个模型,a ClientPage和a ContentSection,where ClientPage has_many :content_sections.我正在使用nested_formgem将两个模型用相同的形式进行编辑.这个工作正常,只要ClientPage至少有一个ContentSection,但如果没有关联ClientSections,using nested_form的link_to_add方法抛出以下内容NoMethodError:
undefined method `values_at' for nil:NilClass
Run Code Online (Sandbox Code Playgroud)
表格结构如下:
<%= nested_form_for page, form_options do |f| %>
# ClientPage fields
# ClientSections
<%= f.link_to_add "Add new section", :content_sections %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
只要至少有一个ClientSection与页面关联,这可以正常工作.一旦没有,就会抛出错误.删除link_to_add也会停止抛出错误.(实际上有第二个嵌套模型ContentSection,如果没有关联的模型,就会出现同样的问题.)
不知道我错过了什么相当明显的东西,但任何指针或建议将不胜感激.
最后解决了这个错误 - 错误是由于我以略微非标准的方式使用gem.在表单中,而不是以标准方式呈现所有内容部分:
<%= f.fields_for :content_sections do |section_form| %>
# section fields
<% end %>
Run Code Online (Sandbox Code Playgroud)
我把它放在一个循环中,因为我需要每个项目的索引(它不存储在模型本身中):
<% page.content_sections.each_with_index do |section, index| %>
<%= f.fields_for :content_sections, section do |section_form| %>
# section fields
<% end %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
这样做的问题是,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 %>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
874 次 |
| 最近记录: |