【问题标题】:Dynamically adding fields to simple_form with CoffeeScript使用 CoffeeScript 将字段动态添加到 simple_form
【发布时间】:2017-09-13 09:35:52
【问题描述】:

我有一个使用 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)

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

【问题讨论】:

  • 你不能用链接标签代替按钮标签吗?这样你就可以防止你的表单被提交

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


【解决方案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 部分:

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

【讨论】:

  • 我最终实现了这个。这是一个更好、更简洁的架构,它很好地服务于我的应用程序。谢谢
猜你喜欢
  • 2014-03-27
  • 1970-01-01
  • 2012-10-04
  • 2017-10-07
  • 2011-11-08
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2010-11-16
相关资源
最近更新 更多