【发布时间】:2015-10-07 05:33:28
【问题描述】:
更新:我正在尝试将表单字段添加/删除到涉及多个模型的嵌套表单。我看过 Ryan Bates 的“Dynamic Forms”railscast,我使用Cocoon Gem 提到了this article。在那篇文章之后,除了 child_index 之外,一切都完美无缺。 child_index 仅出现在第一个 :kid 输入字段 (:name) 和第一个 :pet 输入字段(:name 和 :age)上。然后它会返回到正在添加的字段的真实性令牌。
我已经删除了所有的 JS 和辅助方法,而是使用了一些内置在 JS 中的 Cocoon 方法。
我通过从application.html.erb 文件中删除= javascript_include_tag :cocoon 解决了单击“添加”会添加两个字段而不是一个字段的问题。
我已尝试添加 jQuery 和表单助手,但我不确定我是否正确输入了代码。
(我已更改模型对象以使关系更清晰)
parent.rb 文件:
class Parent < ActiveRecord::Base
has_many :kids
has_many :pets, through: :kids # <<<<<< ADDED KIDS USING 'through:'
kid.rb 文件:
class Kid < ActiveRecord::Base
belongs_to :parent
has_many :pets
accepts_nested_attributes_for :pets, reject_if: :all_blank, allow_destroy: true
validates :name, presence: true
pet.rb 文件:
class Pet < ActiveRecord::Base
belongs_to :kid
validates :name, presence: true
validates :age, presence: true
这是我的 _form.html.erb 文件:
<%= form_for @parent do |f| %>
<% if @parent.errors.any? %>
<div class="alert alert-danger">
<h3><%= pluralize(@student.errors.count, 'Error') %>: </h3>
<ul>
<% @student.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="inline">
<div>
<%= f.fields_for :kids do |kid| %>
<%= render 'kid_fields', f: kid %>
<% end %>
<div>
<%= link_to_add_association "Add Kid", f, :kids, id: 'add_kid',
'data-association-insertion-method' => 'before',
'data-association-insertion-traversal' => 'closest' %>
</div>
<% end %>
</div>
</div>
<div class="form-actions">
<%= f.submit 'Create Parent', class: 'btn btn-primary' %>
</div>
<% end %>
这是我的 _kid_fields.rb 文件:
<div class="nested-fields">
<div class="kid-fields inline">
<%= f.hidden_field :_destroy, class: 'removable' %>
<%= f.text_field :name, class: 'form-control', placeholder: 'Kid's Name', id: 'kid-input' %>
<div>
<%= link_to_remove_association 'Remove Kid', f %>
</div>
<%= f.fields_for :pets do |pet| %>
<%= render 'pet_fields', f: pet %>
<% end %>
</div>
<div>
<%= link_to_add_association "Add Pet", f, :pets, id: 'add_pet',
'data-association-insertion-method' => 'before' %>
</div>
</div>
这是我的 _pet_fields.rb 文件:
<div class="nested-fields">
<div class="pet-fields">
<%= f.hidden_field :_destroy, class: 'removable' %>
<%= f.text_field :name, placeholder: 'Pet Name', id: 'pet-name-input' %>
<%= f.text_field :age, placeholder: 'Pet Age', id: 'pet-age-input' %>
<%= link_to_remove_association 'Remove Pet', f, id: 'remove_pet' %>
</div>
</div>
【问题讨论】:
标签: jquery ruby-on-rails forms nested-forms