使用 CoffeeScript 将字段动态添加到 simple_form

Dynamically adding fields to simple_form with CoffeeScript

我有一个 Rails 5.1.3 应用程序正在使用 simple_form 3.5

我有一个 Books table,其中有一个包含 authors 的 Postgres 数组列。我已经设法构建了所有逻辑以成功填充和保存数组,但是我正在努力使用 CoffeeScript 向表单动态添加新的作者字段。

new.html.erb

<%= simple_form_for @book do |f| %>
    <%= f.input :title %>
    <%= f.input :subtitle %>
    <%= f.input :authors, as: :array %>
    <%= f.button :submit, "Add aditional author", class: "add-author-button" %>
    <%= f.input :description %>
    <%= f.button :submit %>
<% end %>

array_input.coffee

$(document).ready ->
  $('.add-author-button').on 'click', @addAuthorField

  addAuthorField: (ev) ->
    ev.preventDefault()
    $lastAuthorField = $('input[name="book[authors][]"]:last-of-type').clone()
    $lastAuthorField.val("")
    $(".text.optional.book_authors").append($lastAuthorField)

我遇到的问题是,当我单击 'Add additional author' 按钮时,表单会提交,而不是将空白文本字段附加到表单。如果我让其他列的验证失败,表单会重新呈现一个额外的作者字段。

您应该探索 cocoon。它可以满足您的需求,而且可能会做得更好,如果您想编辑同一条记录、删除作者等怎么办?

鉴于您的模型具有以下配置:

class Book < ActiveRecord::Base
  has_many :authors, inverse_of: :book
  accepts_nested_attributes_for :authors, reject_if: :all_blank, allow_destroy: true
end

class Author < ActiveRecord::Base
  belongs_to :book
end

你的表格:

<%= simple_form_for @book do |f| %>
  <%= f.input :title %>
  ...
  <h3>Authors</h3>
  <div id="authors">
    <%= f.simple_fields_for :authors do |author| %>
      <%= render 'author_fields', f: author %>
    <div class="links">
      <%= link_to_add_association 'add author', f, :authors %>
    </div>
  </div>
  <%= f.submit %>

还有一个 _author_fields 部分:

<div class="nested-fields"
  <%= f.input :name %>
  <%= link_to_remove_association 'remove author', f %>
</div>