简体   繁体   English

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

[英]Dynamically adding fields to simple_form with CoffeeScript

I have a Rails 5.1.3 app that is using simple_form 3.5 我有一个正在使用simple_form 3.5的Rails 5.1.3应用程序

I have a Books table and within that a Postgres array column that holds authors . 我有一个Books表,在其中包含authors的Postgres数组列中。 I've manage to build all the logic to successfully populate and save the array, however I'm struggling with dynamically adding a new author field to the form using CoffeeScript. 我已经设法构建了所有逻辑以成功填充并保存数组,但是我在努力使用CoffeeScript向表单中动态添加新的author字段。

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)

The problem I have is that when I click the 'Add additional author' button the form submits rather than appending a blank text field to the form. 我遇到的问题是,当我单击“添加其他作者”按钮时,表单将提交而不是将空白文本字段添加到表单。 If I let the validations for the other columns fail, the form re-renders with an extra author field. 如果我让其他列的验证失败,则该表单会重新呈现一个额外的author字段。

You should explore cocoon . 你应该探索 It does what you want, and it probably does it better, what if you want to edit the same record, remove authors, etc? 如果您要编辑同一条记录,删除作者等,该怎么做,并且可能会做得更好?

Given that your models have the following configuration: 假设您的模型具有以下配置:

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

Your form: 您的表格:

<%= 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 %>

And a _author_fields partial: 和_author_fields部分:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM