所以我才刚刚开始使用 RoR,并认为我也写了一个带有 API 端点的基本博客。问题是我的 api 请求似乎被路由到了错误的控制器,
我有以下作为我的 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
。
甚至rake routes
给了我预期的路线,但实际上击中这些端点失败了。的输出rake routes
如下:
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 上发现的唯一类似问题是嵌套命名空间路由到错误的控制器,但是,那里没有公认的答案,已经一年了。也许另一种尝试将有助于解决此问题