在 ruby​​ on rails 中选择复选框传递数组 [英] Select checkbox pass array in ruby on rails

查看:22
本文介绍了在 ruby​​ on rails 中选择复选框传递数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何传递数组的值?选中的复选框.

How can I pass the value of array? of the selected checkbox.

在视图中:

= check_box_tag 'user_message_ids[]', user_message.id, false

= link_to "<button>Bulk Delete</button>".html_safe, profile_message_path(user_message), :id => 'user_message_ids', :confirm => "Are you sure?", :method => :delete

我可以把提交按钮放在这个区域的任何地方吗.

and can I place the submit button in any of this area.

喜欢这个:

= form_tag checked_messages_path do
  = check_box_tag 'user_message_ids[]', user_message.id, false
--------objects---------------------------------------------
--------objects---------------------------------------------
--------objects---------------------------------------------
--------objects---------------------------------------------
= submit_tag "Delete Checked"

推荐答案

使用 form_tag

<% form_tag delete_mutiple_items_path do %>
  <table>
    <thead>
      <tr>
        <th></th>
      </tr>
    </thead>
    <tbody>
      <% @items.each do |item| %>
      <tr>
        <td><%= check_box_tag "items[]", item.id %></td>
      </tr>
      <% end %>
    </tbody>
  </table>
  <%= submit_tag "delete Checked" %>
<% end %>

它会将一组 id 传递给控制器​​,例如 {item_ids[]";=>[1"、2"、3"]}

It will pass an array of ids to controller, like {"item_ids[]" => ["1", "2", "3"]}

所以你可以用这些 id 做任何事情

So you can do anything with these ids

仅供参考:http://railscasts.com/episodes/165-edit-多个?view=asciicast

从这里:http://railscasts.com/episodes/17-habtm-checkboxes?view=asciicast

我们的更新方法还有一个小问题.如果我们取消选中所有复选框以从所有类别中删除产品,则更新将无法删除该产品所属的任何类别.这是因为 HTML 表单上的复选框不会返回其值如果未选中,则产品的参数哈希中将不会出现 category_ids,这意味着 category_ids 不会更新.

There is still one small problem with our update method. If we uncheck all of the checkboxes to remove a product from all categories then the update fails to remove any categories the product was in. This is because a checkbox on an HTML form will not have its value sent back if it is unchecked and therefore no category_ids will appear in the product’s parameters hash, meaning that the category_ids are not updated.

要解决这个问题,我们必须修改我们的产品控制器,将 category_ids 参数设置为一个空数组,如果它没有传递给更新操作.我们可以使用 Ruby 的 ||= 运算符来完成此操作,并在更新操作的顶部添加以下内容.

To fix this we have to modify our products controller to set the category_ids parameter to be an empty array if it is not passed to the update action. We can do this using Ruby's ||= operator and add the following like at the top of the update action.

params[:product][:category_ids] ||= []

这将确保如果没有选中任何复选框,则产品会正确更新,使其不属于任何类别.

This will ensure that if none of the checkboxes are checked then the product is updated correctly so that it is in no categories.

这篇关于在 ruby​​ on rails 中选择复选框传递数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆