You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails报错:No route matches [POST] "/admin/users/bulk_actions/delete" 求助

解决Rails批量删除路由错误:No route matches [POST] "/admin/users/bulk_actions/delete"

错误原因

当前代码的核心问题:

  • 前端JS将批量删除请求发送到不存在的路径/admin/users/bulk_actions/delete,且使用POST方法
  • 路由仅定义了/admin/users/bulk_actions的POST和DELETE请求,无带后缀的路由
  • 控制器bulk_actions方法通过params[:action_type]区分操作,而非URL后缀

修复步骤

1. 修正前端视图与JavaScript

统一表单提交路径,通过隐藏字段传递操作类型,动态设置请求方法(删除用DELETE):

<div class="card">
  <div class="card-header">
    User Management
  </div>
  <div class="card-body">
    <%= form_tag(admin_users_bulk_actions_path, method: :post, id: "bulk-actions-form") do %>
      <%= hidden_field_tag :action_type, '', id: 'action-type' %>
      <table class="table table-light table-hover table-striped">
        <thead class="table-dark">
          <tr>
            <th><input type="checkbox" id="select-all" onclick="toggleAllCheckboxes()"></th>
            <th>ID</th>
            <th>Name</th>
            <th>Email</th>
            <th>Last Login Time</th>
            <th>Registration Time</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <% @users.each do |user| %>
            <tr>
              <td><input type="checkbox" name="user_ids[]" value="<%= user.id %>"></td>
              <td><%= user.id %></td>
              <td><%= user.username %></td>
              <td><%= user.email %></td>
              <td><%= user.last_sign_in_at %></td>
              <td><%= user.created_at %></td>
              <td><%= user.status %></td>
            </tr>
          <% end %>
        </tbody>
      </table>

      <div class="button-group">
        <button type="button" class="btn btn-danger" onclick="bulkAction('block')">Block</button>
        <button type="button" class="btn btn-primary" onclick="bulkAction('unblock')">Unblock</button>
        <button type="button" class="btn btn-warning" onclick="bulkAction('delete')">Delete</button>
      </div>
    <% end %>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script>
  function bulkAction(action) {
    var form = document.getElementById("bulk-actions-form");
    var actionTypeField = document.getElementById("action-type");
    var methodField = document.querySelector('input[name="_method"]');

    actionTypeField.value = action;

    if (action === 'delete') {
      if (methodField) {
        methodField.value = 'delete';
      } else {
        var input = document.createElement('input');
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', '_method');
        input.setAttribute('value', 'delete');
        form.appendChild(input);
      }
    } else {
      if (methodField) {
        methodField.remove();
      }
    }

    form.submit();
  }

  function toggleAllCheckboxes() {
    var checkboxes = document.querySelectorAll("input[name='user_ids[]']");
    var selectAllCheckbox = document.getElementById("select-all");

    checkboxes.forEach(function(checkbox) {
      checkbox.checked = selectAllCheckbox.checked;
    });

    selectAllCheckbox.indeterminate = checkboxes.length > 0 && !Array.from(checkboxes).every(checkbox => checkbox.checked) && !Array.from(checkboxes).every(checkbox => !checkbox.checked);
  }
</script>

2. 保留现有路由配置

当前路由已正确定义bulk_actions的POST和DELETE方法,无需修改:

namespace :admin do
  resources :users do
    post :bulk_actions, on: :collection
    post :block, on: :member
    post :unblock, on: :member
    delete :bulk_actions, on: :collection
  end
end

3. 精简控制器代码

删除冗余的bulk_delete方法,统一用bulk_actions处理所有批量操作:

class Admin::UsersController < ApplicationController
  before_action :restrict_to_post_or_delete_request, only: [:bulk_actions, :block, :unblock]
  
  def index
    @users = User.all
  end

  def bulk_actions
    action = params[:action_type]
    case action
    when 'block'
      User.where(id: params[:user_ids]).update_all(status: 'blocked')
      redirect_to admin_users_path, notice: 'Users blocked successfully'
    when 'unblock'
      User.where(id: params[:user_ids]).update_all(status: 'active')
      redirect_to admin_users_path, notice: 'Users unblocked successfully'
    when 'delete'
      User.where(id: params[:user_ids]).destroy_all
      redirect_to admin_users_path, notice: 'Users deleted successfully'
    else
      redirect_to admin_users_path, alert: 'Invalid action'
    end
  end

  def block
    user = User.find(params[:id])
    user.update(status: 'blocked')
    redirect_to admin_users_path, notice: 'User blocked successfully'
  end

  def unblock
    user = User.find(params[:id])
    user.update(status: 'active')
    redirect_to admin_users_path, notice: 'User unblocked successfully'
  end

  private

  def restrict_to_post_or_delete_request
    unless request.post? || request.delete?
      redirect_to root_path, alert: 'Invalid request'
    end
  end
end

验证修复

  1. 运行rails routes | grep bulk_actions确认路由存在:
admin_users_bulk_actions POST   /admin/users/bulk_actions(.:format) admin/users#bulk_actions
                         DELETE /admin/users/bulk_actions(.:format) admin/users#bulk_actions
  1. 勾选用户测试三个批量操作,确认无路由错误且功能正常。

内容的提问来源于stack exchange,提问作者1641_Shourav Chy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:55:03