【问题标题】:Dynamic checkbox with Ajax in Rails在 Rails 中使用 Ajax 的动态复选框
【发布时间】:2015-07-20 22:06:17
【问题描述】:

我有一个表单,其中包含从数据库加载的一些复选框,以及一个将其他项目手动添加到项目表的选项。这是由 Ajax 在下面的代码中完成的......

item_controller.rb

   def manual_item_add
      @manual_item = Item.find(params[:id_item].to_i)     
      respond_to do |format|
        format.js
      end
   end

ma​​nual_item_add.js.erb

$("#items_table").append("<%= escape_javascript(render 'manual_item_add', :manual_item => @manual_item) %>")

_manual_item_add.html.erb

...
<td><%= check_box_tag("manual_items[]", item.id, true) %></td>
...

edit_items.html.erb

  <%= form_tag( {controller:"item", action:"edit_items"}) do %>
      <p align="center">
         <%= select_date(@account.start_date, prefix: 'start_date') %>        
      to 
         <%= select_date(@account.end_date, prefix: 'end_date') %>          
      </p>
      <%= hidden_field_tag 'id_account', @account.id %>
      <table id="items_table" class="subtable" align="center" width="55%"> 

            .... 
          <tr>
             <th colspan="6">Items added manually</th>
          </tr>               
          <tr>
             <th># ID</th>
             <th>Type</th>
             <th>Description</th>
             <th>Ammount</th>
             <th>Date</th>
             <th>Include in the account</th>
          </tr>
   </table>

   <p align="center"><%= submit_tag("Save", class: "btn") %></p>
<% end %>


<%= form_tag( {controller:"item", action:"manual_item_add"}, method:"get", remote: true) do %>
   <h4 align="center">Add item manually</h4>
   <p align="center">Item ID:
     <%= text_field_tag "item_id", nil , size:5, maxlength:5 %>
     <%= submit_tag("Add Item", class: "light_btn") %>
   </p>
<% end %>  

所以...这里的问题是,虽然我看到我正在添加到表中的新复选框(它们正在正常创建),但 "manual_items[]"当我提交结果表单时,strong> 数组没有被传递给控制器​​(顺便说一下,“items_table”在表单定义中)。

有人知道我做错了什么吗?抱歉这个新手问题,我开始使用 Ruby + Rails。

【问题讨论】:

  • 请张贴您的表格,您将在其中附加此内容
  • @Deep 我刚刚包含了表单...您可以看到发送 Ajax 请求的第二个表单 - 第一个表单中的表“items_table”是接收新复选框项目的表- 它在表格内,所以我不知道缺少什么。顺便说一句,项目正在表内创建,但参数“manual_items”在提交后甚至没有出现在请求中。
  • 试试这个:&lt;td&gt;&lt;%= check_box_tag("item[manual_items][]", item.id, true) %&gt;&lt;/td&gt;
  • @Deep,我试过了,但没用...表单提交中没有新参数。不知何故,新的复选框未被识别为表单的一部分。我仍然不知道如何继续......

标签: ruby-on-rails ajax ruby-on-rails-3


【解决方案1】:

很遗憾,我对这个问题没有明确的答案。我尝试过的唯一可行的解​​决方案是使用 JQuery 强制参数成为表单的一部分:

$(document).ready(function() {
   $("#edit_items_form").submit(function(event) {
      $(this).append($("input[name='manual_items[]']:checked"));                
      $(this).submit();
  });  
});

我绝对不喜欢这个解决方案,我想知道为什么这些 Ajax 复选框不会被自动识别为表单的一部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-20
    • 2011-10-18
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    相关资源
    最近更新 更多