我有一个使用 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)
我遇到的问题是,当我单击“添加其他作者”按钮时,表单会提交,而不是在表单中附加空白文本字段。如果我让其他列的验证失败,表单将使用额外的作者字段重新呈现。
最佳答案
您应该探索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>
关于javascript - 使用 CoffeeScript 动态添加字段到 simple_form,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46193939/