乐者为王

Do one thing, and do it well.

Rails中通过Checkbox实现批量删除

在Rails生成的控制器模版中,包含的destroy方法只能处理单个对象,而批量删除要求能够同时处理多个对象,这需要自定义一个批量操作action。批量删除的效果图如下:

table-with-checkboxes

每一行记录的第一列设置成Checkbox,用于标记此行是否被选中。表下方放置一个全选Checkbox,表示全部选中或全部反选。全选和反选的JavaScript代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
<script>
function toggle_checkall(field_name, state) {
  var checkboxes = document.getElementsByTagName('input');
  var count = checkboxes.length;
  for (var i = 0; i < count; i++) {
    if (checkboxes[i].type == "checkbox"
        && checkboxes[i].name == field_name + "_ids[]") {
      checkboxes[i].checked = state;
    }
  }
}
</script>

在routes.rb中配置批量删除action的映射:

1
2
3
resources :departs do
  delete 'destroy_multiple', :on => collection
end

在index.html.erb中添加代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<%= form_tag destroy_multiple_departs_path, method: :delete do %>
<%= submit_tag "删除选中" %>
<table>
  <thead>
    <tr>
      <th><input type="checkbox" onclick="toggle_checkall('depart', this.checked);" /></th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td><%= check_box_tag "depart_ids[]", depart.id %></td>
    </tr>
    <tr>
      <td><%= check_box_tag "depart_ids[]", depart.id %></td>
    </tr>
  </tbody>
</table>
<% end %>

在控制器中添加批量删除实现代码:

1
2
3
4
5
6
7
8
def destroy_multiple
  Depart.destroy(params[:depart_ids]) unless params[:depart_ids].blank?

  respond_to do |format|
    format.html { redirect_to departs }
    format.json { head :no_content }
  end
end

Comments