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

Ruby on Rails自定义REST路由匹配失败求助(遵循AIP-136)

Rails 7 配置AIP-136风格自定义路由解决方法

你的问题出在路由配置多了一个不必要的斜杠,请求路径中book_id和动作后缀是直接用冒号连接的(如/books/1234:doSomething),而你之前的配置里加了/\:doSomething,导致路由无法匹配。

正确的单个路由配置

直接去掉多余的斜杠,将路由写成:

post '/books/:id:doSomething', to: 'books#do_something_handler'
post '/books/:id:doSomeOtherThing', to: 'books#do_some_other_thing_handler'

这样Rails就能正确解析/books/1234:doSomething这类路径,把1234赋值给params[:id],同时匹配固定后缀:doSomething。

批量简化配置(可选)

如果有多个类似的动作,可以用约束或统一分发的方式减少重复代码:

方式1:用scope分组路由

scope '/books/:id' do
  post ':doSomething', to: 'books#do_something_handler', constraints: { doSomething: /doSomething/ }
  post ':doSomeOtherThing', to: 'books#do_some_other_thing_handler', constraints: { doSomeOtherThing: /doSomeOtherThing/ }
end

方式2:统一分发到控制器方法

先配置一个通用路由,通过约束限定允许的动作:

post '/books/:id:action', to: 'books#dispatch', constraints: { action: /doSomething|doSomeOtherThing/ }

然后在BooksController中添加分发方法,根据params[:action]调用对应处理逻辑:

class BooksController < ApplicationController
  def dispatch
    case params[:action]
    when 'doSomething'
      do_something_handler
    when 'doSomeOtherThing'
      do_some_other_thing_handler
    else
      render status: :not_found
    end
  end

  private

  def do_something_handler
    # 这里写doSomething的业务逻辑
  end

  def do_some_other_thing_handler
    # 这里写doSomeOtherThing的业务逻辑
  end
end

内容的提问来源于stack exchange,提问作者Saurav Das

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 12:33:13