如何使用resources创建含api/v2与arbitrary_id的指定路由?
正确的Rails路由配置方案
方法一:用命名空间规整API版本
如果api/v2是API的版本前缀,推荐用命名空间来组织,符合Rails的规范:
namespace :api, path: 'api/v2' do resources :arbitrary do get 'sort_games', on: :member, to: 'arbitrary#sort' end end
- 这个配置会生成你要的
/api/v2/arbitrary/:arbitrary_id/sort_games路径,同时默认要求控制器放在Api模块下(比如app/controllers/api/arbitrary_controller.rb)。 - 要是你不想给控制器加模块,就加个
module: false取消约束:namespace :api, path: 'api/v2', module: false do resources :arbitrary do get 'sort_games', on: :member, to: 'arbitrary#sort' end end
方法二:用作用域直接加前缀
如果只是需要api/v2作为静态路径前缀,不需要模块结构,用scope更直接:
scope '/api/v2' do resources :arbitrary do get 'sort_games', on: :member, to: 'arbitrary#sort' end end
验证配置是否正确
配置完后,跑下面的命令查看生成的路由:
rails routes | grep sort_games
正常会输出类似这样的结果,说明路径正确:
api_v2_arbitrary_sort_games GET /api/v2/arbitrary/:arbitrary_id/sort_games(.:format) arbitrary#sort
你之前写法的问题
原来的代码把api/v2/sort_games嵌套在resources :arbitrary里,会生成/arbitrary/:arbitrary_id/api/v2/sort_games这种颠倒的路径,不符合需求,所以得把api/v2提到外层作为前缀。
内容的提问来源于stack exchange,提问作者Infor Mation
相关产品推荐
相关产品推荐

