Rails - 通过参数传递多个复选框值

Rails - Pass multiple checkbox values through params

我正在使用 Smart listing gem 进行实时过滤。 以下是没有提交和 url 的简单表单。

<%= smart_listing_controls_for(:search) do %>
  <%= simple_form_for :search do |f| %>
    <%= f.input :certificates, collection: Certificate.all, :as => :check_boxes, include_hidden: false, :input_html => {:multiple => true} %>
  <% end>
<% end>

以上代码生成了多个以“证书 ID”为值的复选框。 一旦选中其中一个复选框,智能列表就会向带有参数的控制器发送请求。

Parameters: {"utf8"=>"✓", "search_smart_listing"=>{"_"=>"1", "page"=>"", "per_page"=>"10"}, "authenticity_token"=>"z25rULU5JeeWcEZdpsy0+bz7OJFDWPmXrVGnzPvdG0cjM0ufpc3ydB9+5GywDQkUmcm6RGJnF0C4Yrd0sWpJ6g==", "search"=>{ "certificates"=>["6"]}}

问题是当我 select 多个复选框时,证书数组只有最新值,而不是所有 selected 复选框值。

此外,当复选框被 selected 和 de-selected 时,参数中的证书数组值保持不变。如果取消复选框,我希望从参数中的证书数组中删除该值 selected 并且只希望证书数组只包含所有 selected 复选框值。

以下是为多个复选框之一生成的 html 代码。

<span class="checkbox">
  <label for="search_certificates_5">
    <input class="check_boxes required" type="checkbox" value="5" name="search[certificates][]" id="search_certificates_5">
     Certificate 1
  </label>
</span>

提前致谢:)

由于 smart_listing_controls_forsimple_form_for 都创建了一个 表单 ,您可能遇到的一个问题是您在表单中创建了一个表单,并且既不推荐也不标准。这可能会导致意想不到的结果。

也许可以在没有 simple_form 助手的情况下尝试这样做,像这样(假设 Certificate 具有描述属性):

<%= smart_listing_controls_for(:search) do %>
  <%= Certificate.all.each do |certificate| %>
    <div class="checkbox">
      <label class= "checkbox inline">
        <%= check_box_tag 'search[certificates][]', certificate.id %>
        <%= certificate.description %>
      </label>
    </div>
  <% end %>
<% end %>

更新

此外,智能列表 gem 的当前版本 (v1.1.2) 存在问题不允许使用数组输入。问题出在javascript code. This is fixed on current master branch and was updated recently on latest commit as you can see here.

这部分

要解决此问题,请使用 Gemfile 中的最新提交,如下所示:

gem 'smart_listing', :git => 'https://github.com/Sology/smart_listing.git', :ref => '79adeba'

bundle install 更新 Gemfile 后再次尝试上面的代码。