Type:
Module

You may wish to organize groups of controllers under a namespace. Most commonly, you might group a number of administrative controllers under an admin namespace. You would place these controllers under the app/controllers/admin directory, and you can group them together in your router:

1
2
3
namespace "admin" do
  resources :posts, :comments
end

This will create a number of routes for each of the posts and comments controller. For Admin::PostsController, Rails will create:

1
2
3
4
5
6
7
GET       /admin/posts
GET       /admin/posts/new
POST      /admin/posts
GET       /admin/posts/1
GET       /admin/posts/1/edit
PATCH/PUT /admin/posts/1
DELETE    /admin/posts/1

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

1
2
3
scope module: "admin" do
  resources :posts
end

or, for a single case

1
resources :posts, module: "admin"

If you want to route /admin/posts to PostsController

(without the Admin

module prefix), you could use

1
2
3
scope "/admin" do
  resources :posts
end

or, for a single case

1
resources :posts, path: "/admin/posts"

In each of these cases, the named routes remain the same as if you did not use scope. In the last case, the following paths map to PostsController:

1
2
3
4
5
6
7
GET       /admin/posts
GET       /admin/posts/new
POST      /admin/posts
GET       /admin/posts/1
GET       /admin/posts/1/edit
PATCH/PUT /admin/posts/1
DELETE    /admin/posts/1
controller
  • References/Ruby on Rails/Rails/Classes/ActionDispatch/ActionDispatch::ROUTING/ActionDispatch::Routing::Mapper/ActionDispatch::Routing::Mapper::Scoping

controller(controller, options={}) Instance Public methods Scopes routes to

2025-01-10 15:47:30
defaults
  • References/Ruby on Rails/Rails/Classes/ActionDispatch/ActionDispatch::ROUTING/ActionDispatch::Routing::Mapper/ActionDispatch::Routing::Mapper::Scoping

defaults(defaults = {}) Instance Public methods Allows you to set default parameters

2025-01-10 15:47:30
constraints
  • References/Ruby on Rails/Rails/Classes/ActionDispatch/ActionDispatch::ROUTING/ActionDispatch::Routing::Mapper/ActionDispatch::Routing::Mapper::Scoping

constraints(constraints = {}) Instance Public methods Parameter Restriction

2025-01-10 15:47:30
scope
  • References/Ruby on Rails/Rails/Classes/ActionDispatch/ActionDispatch::ROUTING/ActionDispatch::Routing::Mapper/ActionDispatch::Routing::Mapper::Scoping

scope(*args) Instance Public methods Scopes a set of routes to the given default

2025-01-10 15:47:30
namespace
  • References/Ruby on Rails/Rails/Classes/ActionDispatch/ActionDispatch::ROUTING/ActionDispatch::Routing::Mapper/ActionDispatch::Routing::Mapper::Scoping

namespace(path, options = {}) Instance Public methods Scopes routes to a specific

2025-01-10 15:47:30