Rails中实现批量删除
在Rails生成的控制器模版中,包含的destroy只能处理单个对象,而批量删除要求能够同时处理多个对象,这需要自定义一个批量操作action。批量删除的效果图如下:
每一行记录的第一列设置成checkbox,用于标记此行是否被选中。表下方放置一个全选checkbox,表示全部选中或全部反选。全选和反选的JavaScript代码如下:
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;
}
}
在routes.rb中配置批量删除action:
resources :shops do
collection do
post :import
get :association_brand
post :update_valid
delete :destroy_multiple
end end
在index.html.erb中添加代码:
<%= form_tag destroy_multiple_admin_shops_path, method: :delete do %> <%= submit_tag "删除选中" %> <table> ... <th><input type="checkbox" onclick="toggle_checkall('shop', this.checked);" /></th> ... <td><%= check_box_tag "shop_ids[]", shop.id %></td> ... </table> <% end %>
在controller中添加批量删除实现代码:
def destroy_multiple
if params[:shop_ids].blank?
redirect_to :back, :alert => '请选择待删除项'
else
shops = Shop.find params[:shop_ids]
shops.each do |shop|
shop.destroy
end
end
respond_to do |format|
format.html { redirect_to admin_shops_url }
format.json { head :no_content }
end
end