获取所有选中的复选框值

Get all checked checkboxes values

本文关键字:复选框 获取      更新时间:2024-06-22

我有以下形式:

<%= form_for([company,service], :remote => true) do |f| %>
    <%= health_care_insurances.each do |hc_insurance| %>
        <label><%= hc_insurance.name %></label>
        <input id="health_care_insurance_<%= user.id %>" name="<%= hc_insurance.id %>" value="<%= hc_insurance.id %>" type="checkbox"><br/>
    <% end %>
    ...
<% end %>

提交后,为了获得良好的性能,我希望得到一个包含所有已检查的"hc_insurance.ids"的数组。我知道我可能会使用javascript将它们添加到hidden_field,然后从那里提取它们,但我不确定这是一个好方法。

有没有什么轨道可以从控制器上取下它们?

使所有复选框的名称与数组框相同,如下所示(这将只向后端提交选中的值)

<input id="health_care_insurance_<%= user.id %>" name="health_care_insurence_ids[]" value="<%= hc_insurance.id %>" type="checkbox"><br/>

获取控制器中所有health_care_insurence的id(假设health_care _insurence是单个模型)。

HealthCareInsurence.pluck(:id)