ActionController::RoutingError:未初始化常量BaseController问题求助
Got it, let's break down why you're seeing that uninitialized constant BaseController error and fix it step by step.
The core issue here is a mismatch between your controller's namespace, file structure, and how Ruby resolves constants. When you write < BaseController inside Api::WhiteLabel::V1::CarMakeController, Ruby looks for a BaseController inside the same namespace (Api::WhiteLabel::V1) first, then the top-level namespace. If your file structure doesn't align with the namespace, Rails can't autoload the constant properly.
1. Align File Path with Namespace (Recommended)
Rails relies heavily on convention over configuration, so your controller's file path must mirror its class namespace. Right now you have:
- Class:
Api::WhiteLabel::V1::BaseController - File location:
app/controllers/v1/white_label_api/base_controller.rb
These don't match. For the namespace Api::WhiteLabel::V1, the correct file path should be:app/controllers/api/white_label/v1/base_controller.rb
Move your BaseController to that path, and place CarMakeController in the same directory:app/controllers/api/white_label/v1/car_make_controller.rb
Now you can keep your inheritance code as-is:
class Api::WhiteLabel::V1::CarMakeController < BaseController end
Since both controllers are in the exact same namespace, Ruby will find BaseController without issues.
2. Use the Full Namespace for BaseController
If rearranging files isn't an option, explicitly reference the full namespace of your base controller when inheriting:
class Api::WhiteLabel::V1::CarMakeController < Api::WhiteLabel::V1::BaseController end
This tells Ruby exactly where to find the BaseController constant, skipping the relative namespace lookup that was failing before.
3. Confirm Autoload Paths (Last Resort)
By default, Rails autoloads all subdirectories under app/controllers, but if your custom directory isn't being picked up, you can add it manually in config/application.rb:
config.autoload_paths << Rails.root.join('app/controllers/v1/white_label_api')
Note: This is a temporary fix. The real solution is aligning your file structure with the namespace, as it keeps your codebase consistent with Rails conventions.
内容的提问来源于stack exchange,提问作者Haseeb Ahmad

