【问题标题】:Rails 5 fields_for nesting under a collectionRails 5 fields_for嵌套在集合下
【发布时间】:2017-06-05 20:53:42
【问题描述】:

所以我有一个具有这种结构的模型:

document { 
  structure { 
    id, 
    ... 
  }, 
  fields { 
    field { 
      id,
      ...
    }, 
    value { 
      ... 
    } 
  } 
}

我正在尝试为字段组合一个表单,字段看起来像这样:

<input type="hidden" name="document[fields][0][field][id]" />
<input type="text" name="document[fields][0][value]" />

<input type="hidden" name="document[fields][1][field][id]" />
<input type="text" name="document[fields][1][value]" />

...

这是我目前正在做的:

  <%= document.fields.each_with_index do |df, i| %>
    <%= f.fields_for "fields[]", df do |builder| %>
      <p>
        <%= builder.label df.field.name %>
        <%= builder.fields_for :field do |field_builder| %>
          <%= field_builder.hidden_field :id, value: df.field.id %>
        <% end %>

        <%= builder.fields_for :value do |value_builder| %>
          <%= render df.field.edit_view, field: df.field, builder: value_builder %>
        <% end %>
      </p>
    <% end %>
  <% end %>

但生成的字段名称是:

document[fields][field][id]
document[fields][value][value]

换句话说,索引丢失了。

使用 &lt;%= builder.hidden_field :id, value: df.field.id %&gt; 会产生正确的格式但没有索引(因为字段对象还没有 id):document[fields][][id] 但这不是值的选项,因为可能涉及多个字段。

有没有办法使用表单助手来做到这一点,或者我正在做的事情太不靠谱了?

编辑:以下是涉及的模型:

我们的想法是为文档设置一组可配置的字段。该结构决定了可用的字段,document_field 是文档和包含值的字段之间的关系。

class Field < ApplicationRecord
    belongs_to :structure
end

class Document < ApplicationRecord
    belongs_to :structure
    has_many :document_fields

class DocumentField < ApplicationRecord
  belongs_to :document
  belongs_to :field

class Structure < ApplicationRecord
    has_many :fields

【问题讨论】:

  • 你能添加你的模型,尝试重现你的场景吗?
  • 已添加到帖子中

标签: ruby-on-rails form-helpers


【解决方案1】:

您应该配置nested attributes setup on your models,在控制器上构建那些嵌套关系,并在form_for 块中实例化一个对象,而不是传递引用符号。

【讨论】:

  • 这适用于document_field [field],但不适用于价值,它不是一个单独的模型,它只是一个包含任意结构化数据的JSON对象......我如何使用像accepts_nested_attributes_for这样的东西那个?
猜你喜欢
  • 2018-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多