加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – 使用带有空关联的nested_form gem时出错

发布时间:2020-12-17 03:05:30 所属栏目:百科 来源:网络整理
导读:在我的rails应用程序中,我有两个模型,ClientPage和ContentSection,其中ClientPage has_many:content_sections.我正在使用nested_form gem来使用相同的表单编辑两个模型.只要ClientPage具有至少一个ContentSection,但是如果没有关联的ClientSections,则使用n
在我的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 %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读