【问题标题】:Updating model after unchecking all checkboxes取消选中所有复选框后更新模型
【发布时间】:2018-01-23 06:01:03
【问题描述】:

我有一个用于创建设备的表单,用于选择哪些用户将拥有设备。因此,其中一个字段带有选择用户的复选框:

<% User.all.each do |user| %>
  <label class="checkbox-inline">
    <%= f.check_box :user_ids, {:multiple => true}, user.id, nil  %> <%= user.name %>
  </label>
<% end >

它生成:

<input type="checkbox" value="1" name="device[user_ids][]" id="device_user_ids_1">
<input type="checkbox" value="2" name="device[user_ids][]" id="device_user_ids_2">
<input type="checkbox" value="3" name="device[user_ids][]" id="device_user_ids_3">
<input type="checkbox" value="4" name="device[user_ids][]" id="device_user_ids_4">

编辑对象时,如果我选中任何一个框,参数:user_ids 将与其他参数一起传递给控制器​​。但是如果我不选中任何框,以防我现在不希望任何用户链接到设备,则参数传递给控制器​​时参数:user_ids 不存在。

如果没有选中任何复选框,我该怎么做才能将"user_ids"=&gt;[] 作为参数?

【问题讨论】:

  • f.check_box 生成什么代码?将其添加到您的帖子中。我认为 Rails check_box 生成器在复选框之前添加了&lt;input type="hidden" name="user_ids"&gt;,以修复您的确切情况,即消失的参数错误。
  • 我更新了问题。它产生了我所期待的......
  • 如果没有选中任何复选框,则必须签入控制器并从设备对象中删除所有user_ids
  • @Subash 但是如果参数没有被传递,我如何在控制器中检查它?
  • @LuizHenrique 你可以通过params[:device][:user_ids].length 来查看是否选择了任何ID

标签: ruby-on-rails checkbox


【解决方案1】:

您可以在表单中为复选框声明一个隐藏字段,当未选中复选框时,它将被发送为空

<%= f.hidden_field "device[user_ids][]", nil %>

然后

<% User.all.each do |user| %>
    <label class="checkbox-inline">
        <%= f.check_box :user_ids, {:multiple => true}, user.id, name:  'device[user_ids][]' %> <%= user.name %>
    </label>
<% end >

希望能帮到你

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-23
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多