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

Rails 6:如何通过请求路径与方法获取对应调用方法名

解决Rails中间件中映射ActiveAdmin路由到方法名的问题

你可以利用Rails的路由识别功能,通过请求路径和方法直接解析出对应的路由命名(也就是你需要的“后端调用方法名”)。以下是修改后的中间件代码:

class AccountabilityMiddleware
  def initialize(app)
    @app = app
  end

  def call(env)
    dup._call env
  end

  def _call(env)
    @status, @headers, @response = @app.call(env)

    req = Rack::Request.new(env)
    if !req.get? && req.path.starts_with?('/admin') && !req.path.starts_with?('/admin/login')
      method_name = nil
      begin
        # 解析请求对应的路由信息
        route_info = Rails.application.routes.recognize_path(
          req.path,
          method: req.request_method.downcase.to_sym
        )
        # 获取路由命名并转为字符串
        method_name = route_info[:name]&.to_s
      rescue ActionController::RoutingError
        # 处理路由不存在的情况,可根据需求调整
        method_name = "unrecognized_route"
      end

      Accountability.create!(
        user: env['warden'].user,
        url: req.path,
        method: req.request_method,
        params: req.params.except(:controller, :action), # 过滤路由自带的冗余参数
        method_name: method_name,
        response_status: @status,
        response: @response.body,
      )
    end

    [@status, @headers, @response]
  end
end

关键说明:

  • 调用Rails.application.routes.recognize_path可根据请求路径和方法,解析出路由元信息,其中:name字段就是路由的命名辅助方法名(比如你提到的new_admin_my_model)。
  • 用begin-rescue包裹是为了处理无效路由的情况,避免中间件崩溃。
  • 存储params时过滤:controller和:action参数,避免冗余数据。

ActiveAdmin生成的路由命名遵循统一规则,比如:

  • POST /admin/my_models 对应路由命名 create_admin_my_models
  • GET /admin/my_models/new 对应路由命名 new_admin_my_model
  • PATCH /admin/my_models/1 对应路由命名 update_admin_my_model

内容的提问来源于stack exchange,提问作者Bruno Aguiar de Souza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 02:06:35