Rails 命名空间路由到错误的控制器

编程入门 行业动态 更新时间:2024-10-28 14:22:09
本文介绍了Rails 命名空间路由到错误的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我才刚刚开始使用 RoR,并认为我也用 API 端点做一个基本的博客.问题是我的 api 请求似乎被路由到了错误的控制器,

So I'm just beginning with RoR and figured I do a basic blog with API endpoints aswell. The problem is that my api requests seem to be routed to the wrong controller,

我有以下作为我的 routes.rb

I have the following as my routes.rb

Blog::Application.routes.draw do namespace :api do namespace :v1 do resources :articles end end end

我还有controllers/api/v1/articles_controller.rb,内容如下:

module API module V1 class ArticlesController < ApplicationController respond_to :json def index respond_with Article.all end end end end

我的逻辑是,当我点击 localhost:3000/api/v1/articles 时,这应该是响应的控制器,但是实际响应的控制器是控制器的根目录 (controllers/articles_controller.rb) 而不是 /api/v1 路径中的根目录.当我移除实际响应的控制器时,我会得到 uninitialized constant Api::V1::ArticlesController .

My logic says that when I hit localhost:3000/api/v1/articles, this should be the Controller to respond, however the actual Controller that responds is the one in the root of controllers (controllers/articles_controller.rb) and not the one in the /api/v1 path. When I remove the Controller that actually responds, I'll get uninitialized constant Api::V1::ArticlesController instead.

即使 rake routes 也给了我预期的路由,但实际上到达这些端点失败了.rake routes 的输出如下:

Even rake routes gives me the expected routes, however actually hitting those endpoints fails. Output of rake routes is the following:

api_v1_articles GET /api/v1/articles(.:format) api/v1/articles#index POST /api/v1/articles(.:format) api/v1/articles#create new_api_v1_article GET /api/v1/articles/new(.:format) api/v1/articles#new edit_api_v1_article GET /api/v1/articles/:id/edit(.:format) api/v1/articles#edit api_v1_article GET /api/v1/articles/:id(.:format) api/v1/articles#show PUT /api/v1/articles/:id(.:format) api/v1/articles#update DELETE /api/v1/articles/:id(.:format) api/v1/articles#destroy

我在 SO 上发现的唯一类似问题是 嵌套命名空间路由出错控制器 但是,那里没有公认的答案,而且已经一年了.也许另一次尝试将有助于解决这个问题

The only similar question I found on SO is nested namespace route going to wrong controller however, there's no accepted answer there and it's been a year. Maybe another attempt will help resolve this issue

推荐答案

您的模块是 API,但 Rails 正在寻找 Api.Ruby 的模块区分大小写.

Your module is API, but Rails is looking for Api. Ruby's modules are case-sensitive.

更多推荐

Rails 命名空间路由到错误的控制器

本文发布于:2023-10-26 10:50:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路由   控制器   错误   空间   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!