使用动态字段发送键数组

时间:2019-08-25 07:10:46

标签: ruby-on-rails ruby ruby-on-rails-5.2

我需要一种使用fields_for发送键数组的方法。唯一的问题是我正在使用一些JavaScript代码构建动态字段。让我分享我的代码

todos / _form.html.erb

<%= form_for(@todo_list) do |f| %>

  <div class="form-inputs">
    <%= f.text_field :name %>
  </div>

  <table class='table'>
    <thead>
      <tr>
        <th>Complete List</th>
        <th>Name</th>
        <th>option</th>
      </tr>
    </thead>
    <tbody class='fields'>
      <%= f.fields_for :tasks do |builder| %>
        <tr>
          <td>
            <%= f.hidden_field :_destroy %>
            <%= link_to 'Delete', '#', class: 'remove_record' %>
          </td>
          <td><%= f.text_field :completed %></td>
          <td>
            <%= f.select :name, [['ANiket','aniket'],['Shivam','shivam']], include_blank: 'Select a Group', class: 'form-control' %>
          </td>
          <td><%= f.text_field :option %></td>
        </tr>
      <% end %>
    </tbody>
  </table>

  <div class="form-actions">
    <%= f.button :submit %>
    <%= link_to_add_row('Add Task', f, :tasks, class: 'btn btn-primary') %>
  </div>
<% end %>

application_helper.rb

module ApplicationHelper
   def link_to_add_row(name, f, association, **args)
    new_object = f.object.send(association).klass.new
    id = new_object.object_id
    fields = f.fields_for(association, new_object, child_index: id) do |builder|
      render(association.to_s.singularize, f: builder)
    end
    link_to(name, '#', class: "add_fields " + args[:class], data: {id: id, fields: fields.gsub("\n", "")})
  end
end

我的js代码

  $(document).on('click', '.remove_record', function(event) {
    $(this).prev('input[type=hidden]').val('1');
    $(this).closest('tr').remove();
    return event.preventDefault();
  });

  $(document).on('click', '.add_fields', function(event) {
    var regexp, time;
    time = new Date().getTime();
    regexp = new RegExp($(this).data('id'), 'g');
    $('.fields').append($(this).data('fields').replace(regexp, time));
    return event.preventDefault();
  });

因此,目前,在我的情况下,选项字段是一个数组。现在,这些字段正像下面一样形成

 <input type="text" name="todo[tasks_attributes][1566716366848][completed]" id="todo_tasks_attributes_1566716366848_completed">

    <input type="text" name="todo[tasks_attributes][1566716366848][option]" id="todo_tasks_attributes_1566716366848_option">

因此,我需要一种将 option 字段作为键数组发送的方法

1 个答案:

答案 0 :(得分:1)

花费大量时间后,我找到了解决方案。如果在我的情况下浏览 f 的form_object,我会发现 object_name 字段,其中包含数据。

<%= f.text_field :option, name: f.object_name + "[option][]"  %>

所以,它将给我这个

<input name="todo[tasks_attributes][1566716366848][option][]" type="text" value="" id="todo_tasks_attributes_1566716366848_option">