ActionController :: RoutingError:未初始化的常量Api :: V1 :: ApiController
我有用于控制用户任务的Rails 5 API项目,我有以下错误,但并不总是对于相同的控制器和路由。
ActionController::RoutingError: uninitialized constant Api::V1::ApiController
我向您描述了一些我的项目,以更详细地解释错误。
应用结构
路线
scope module: 'api' do namespace :v1 do # => Login routes scope module: 'login' do match 'login', to: 'sessions#login', as: 'login', via: :post end # => Team routes scope module: 'team' do # => no admin routes resources :tasks, except: [:index] do collection do match ':view', to: 'tasks#index', as: 'tasks', via: [:get, :post] end end end end end
API控制器
module Api class ApiController < ApplicationController def respond_with_errors(object) render json: {errors: ErrorSerializer.serialize(object)}, status: :unprocessable_entity end end end
团队控制员
module Api::V1 class Team::TeamController < ApiController
任务控制器
module Api::V1 class Team::TasksController < Team::TeamController
登录控制器
module Api::V1 class Login::LoginController < ApiController
会话控制器
module Api::V1 class Login::SessionsController < Login::LoginController
当我执行登录路由并且在任务路由之后,我得到了最后路由中的错误以及团队模块中的所有路由。 如果我更改项目并保存它(只有一个空格)然后我执行任务路由和登录路由后,我得到最后路由中的错误和登录模块中的所有路由。
它没有任何意义……
Rails服务器出现此错误
你应该在inheritance – ::Api::ApiController
时使用正确的常量:
module Api::V1 class Team::TeamController < ::Api::ApiController
因为否则它正在搜索Api::V1::ApiController
,但是应该搜索Api::ApiController
现在你有Api::ApiController
。
您的app/controllers/api/v1/api_controller.rb
缺少命名空间中的V1
module Api::V1 class ApiController < ApplicationController .. end end
UPDATE
如果您的ApiController
在V1
文件夹之外,那么您应该这样做
module Api::V1 class Team::TeamController < ::Api::ApiController