使用CoffeeScript动态地向simple_form添加字段

时间:2017-09-13 09:35:53

标签: javascript ruby-on-rails coffeescript simple-form

我有一个使用simple_form 3.5

的Rails 5.1.3应用程序

我有一个Books表,其中包含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)

我遇到的问题是,当我单击“添加其他作者”按钮时,表单会提交而不是在表单中附加空白文本字段。如果我让其他列的验证失败,则表单将使用额外的作者字段重新呈现。

1 个答案:

答案 0 :(得分:1)

你应该探索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 partial:

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