Rails 3 namespace routing

When I try to access the following URL, I get a 404 error page :

dev.mydomain.com/api

whereas the routes.rb file indicates that this route exists:

routes.rb

constraints :subdomain => 'dev' do
  root :to => 'developers/main#index', :as => :developers
  namespace 'api', :as => :developers_api do
    root :to => 'developers/apidoc/main#index'
  end
end

rake routes

         developers   /(.:format)      {:subdomain=>"dev", :controller=>"developers/main", :action=>"index"}
developers_api_root   /api(.:format)   {:subdomain=>"dev", :controller=>"api/developers/apidoc/main", :action=>"index"}

controller

/app/controllers/developers/apidoc/main_controller.rb

class Developers::Apidoc::MainController < Developers::BaseController
  def index
  end
end

magazines

[router]: GET dev.mydomain.com/api dyno=web.1 queue=0 wait=0ms service=14ms status=404 bytes=0
[web.1]: Started GET "/api"
[web.1]: ActionController::RoutingError (uninitialized constant Api::Developers)
+5
source share
3 answers

, , api/developers/apidoc/main, Developers::Apidoc::MainController. api, Api - Api::Developers::Apidoc::MainController.

+5

, , - , . :

Routing Error

uninitialized constant Api::Developers

, :

namespace "api" do
  namespace "developers" do
    ...
  end
end

/ app/controllerlers/api/developers/

+3

TL; DR namespace scope

 Rails.root
  |
  +-- app/
  |    |
  |    +-- controllers/
  |         |
  |         +-- jobs_controller.rb
  +-- config/
       |
       +-- routes.rb

routes.rb ActionController::RoutingError: uninitialized constant Api:

namespace :api do
  namespace :v1 do
    resources :jobs
  end
end

:

scope :api do
  scope :v1 do
    resources :jobs 
  end
end

Rails Routing from Outside In:

Namespace will automatically add the area :as, as well as :moduleand :path.

Indeed, a namespace is just a wrapper around an area with a set of predefined options:

# File actionpack/lib/action_dispatch/routing/mapper.rb, line 871
def namespace(path, options = {})
  path = path.to_s

  defaults = {
    module:         path,
    path:           options.fetch(:path, path),
    as:             options.fetch(:as, path),
    shallow_path:   options.fetch(:path, path),
    shallow_prefix: options.fetch(:as, path)
  }

  scope(defaults.merge!(options)) { yield }
end
+1
source

All Articles