ruby-on-rails - 在 ruby​​ on rails 中选择复选框传递数组

标签 ruby-on-rails ruby controller

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

在 View 中:

= 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

我可以将提交按钮放在这个区域中吗?

喜欢这个:

= 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 block

<% 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 传递给 Controller ​​,例如 {"item_ids[]"=> ["1", "2", "3"]}

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

仅供引用:http://railscasts.com/episodes/165-edit-multiple?view=asciicast

已更新(一个小陷阱)

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

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.

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 - 在 ruby​​ on rails 中选择复选框传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11965248/

相关文章:

ruby-on-rails - Webpacker 仅创建 manifest.json 文件,因此缺少 Assets

ruby-on-rails - 使用 ElasticSearch + Tire 搜索多个术语

asp.net-mvc - 单元测试 Asp.net MVC Controller 操作

image - Grails Controller 中的资源路径

ruby-on-rails - ElasticSearch 搜索多种类型

ruby-on-rails - 多个子域不断重定向到根路径

ruby - 为什么带赋值的三元运算符不返回预期的输出?

ruby-on-rails - 在 Ruby on Rails 中@或不@

controller - Kubernetes Pod 动态环境变量

ruby-on-rails - 何时使用关联扩展与命名范围?