1
  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" %>

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

4

1 回答 1

1

我看过这个演员表,这似乎不是处理嵌套属性的“添加更多”链接的最佳解决方案。

基本上,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 将自动保存子对象,因为每个子对象都由 accept_nested_atributes 格式唯一标识

于 2013-07-07T19:13:06.993 回答