jhgju77
jhgju77

Reputation: 1151

how to make dynamic namespace or scopes route in rails

I am trying to make admin route with namespace but it doest trigger to the route

I run rails g controller admin

it created the file app/controllers/admin_controller.rb , app/views/admin/index.html.haml

my namespace look like this

namespace :admin do
   controller :admin do
     get '/', :index
   end
end

it doesn't trigger to localhost:3000/admin it said not found for that route any idea ??

Upvotes: 1

Views: 641

Answers (2)

max
max

Reputation: 102045

namespace not only adds a path prefix but it also adds a module nesting to the expected controller. For example:

namespace :blog do
  resources :posts
end

Will create the route /blog/posts => Blog::PostsController#index.

In your example Rails expects the controller to be defined as:

# app/controllers/admin/admin_controller.rb
module Admin
  class AdminController
    # GET /admin
    def index
    end
  end
end

If you just want to add a path prefix or other options to the routes without module nesting use scope instead:

scope :admin, controller: :admin do
  get '/', action: :index
end

This will route /admin to AdminController#index

But if this just a one off route you could just write:

get :admin, to: 'admin#index'

Upvotes: 1

ellitt
ellitt

Reputation: 833

Your controller path needs to be in the admin namespace.

So the filename for the admin controller needs to be app/controllers/admin/admin_controller.rb.

Upvotes: 0

Related Questions