嵌套字段帮助程序方法


  def link_to_add_nested_fields(name, f, association, klasss, type) 
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    field = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize + "_#{type}", f: builder)
    end
    link_to(name, '#', class: klasss, data: {id: id, type: field.gsub("n", "")})   
  end

我正在尝试自定义一段我从这里获得的帮助程序代码 http://railscasts.com/episodes/196-nested-model-form-revised,但我在类型参数方面遇到了问题。使用此帮助程序的示例;

<%= link_to_add_nested_fields "Add custom field", f, :fields, "add_fields","fields" %>

问题肯定出在类型参数上,有谁知道我该如何解决这个问题?谢谢

我已经看到了这个转换,这似乎不是处理嵌套属性的"添加更多"链接的最佳解决方案。

基本上,accepts_nested_attributes的工作方式是这里的关键。

在您的controller

parent.child.build

只需构建一次即可初始查看。这将使该字段最初在页面重新加载时显示。

在你的.erb template

<% parent.children.each do |child| %>
<div class="child_fields">
    <%= render "the child fields partial" %>
</div>
<% end %>
<%= link_to "Add More", "#", class: "add_more_link" %>
<% javascript_include_tag "js_file_to_handle_add_more_link" %>

在您的"js_file_to_handle_add_more_link.js"

首先,使用以下方法对现有子字段进行计数:

$('.child_fields').size();

现在,创建 id 为的 html 字段:

parent_children_attributes_" + count + "_attribute_name"

并命名为:

"parent[children_attributes]["+ count +"][attribute_name]"

每组子字段都应具有唯一的值计数。此外,这里的父母是单数,而孩子是复数。

而且,就是这样。

现在,当表单提交时,rails 将自动保存子对象,因为每个子对象都由 accepts_nested_atributes 格式唯一标识

最新更新