问题描述
所以我才刚刚开始使用 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
我的逻辑是,当我点击 http://localhost:3000/api/v1/articles
时,这应该是响应的控制器,但是实际响应的控制器是控制器的根目录 (controllers/articles_controller.rb
) 而不是 /api/v1
路径中的根目录.当我移除实际响应的控制器时,我会得到 uninitialized constant Api::V1::ArticlesController
.
My logic says that when I hit http://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 命名空间路由到错误的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!