Routing error - uninitialized constant

Adding this answer to get clarity on namespace & scope.

When you use namespace, it will prefix the URL path for the specified resources, and try to locate the controller under a module named in the same manner as the namespace.

# config/routes.rb
namespace :admin do
  resources :posts, only: [:index]
end

# rake routes
Prefix Verb URI    Pattern                   Controller#Action
admin_posts GET    /admin/posts(.:format)    admin/posts#index

When we add scope, it will just map the controller action for the given scope patterns. No need to define controller under any module.

# config/routes.rb
scope :admin do
  resources :posts, only: [:index]
end

# rake routes
Prefix Verb URI    Pattern                   Controller#Action
admin_posts GET    /admin/posts(.:format)    posts#index

Note that, controller is just posts controller without any module namespace.

If we add a path option to scope it will map to the controller with the path option specified as follows

# config/routes.rb
scope module: 'admin', path: 'admin' do
  resources :posts, only: [:index]
end

# rake routes
Prefix Verb URI    Pattern                   Controller#Action
admin_posts GET    /admin/posts(.:format)    admin/posts#index

Note that the controller now is under admin module.

Now, if we want to change the name of path method to identify resource, we can add as option to scope.

# config/routes.rb
namespace module: 'admin', path: 'admin', as: 'root' do
  resources :posts, only: [:index]
end

# rake routes
Prefix Verb URI    Pattern                  Controller#Action
root_posts GET    /admin/posts(.:format)    admin/posts#index

You can see the change in the Prefix Verb.

Hope it helps others.


According to http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing you should use scope instead of namespace.

If you want to route /admin/posts to PostsController (without the Admin:: module prefix), you could use:

scope "/admin" do
  resources :posts, :comments
end

Late answer, but still might be helpful:

scope '/v1' do  
  resources :articles, module: 'v1'
end

controller

# app/controller/v1/articles_controller.rb
class V1::ArticlesController < ApplicationController

end

Now you should be able to access this url:

http://localhost:3000/v1/articles