0

I'm currently using Devise for user authentication and I would like to implement a backend admin to control the creation of users in the admin panel.

I have generated an admin controller and I've added a namespace to my routes.

-> routes.rb

namespace :admin do
  resources :users
end

When I rake routes I get the following

         admin_users GET    /admin/users(.:format)            admin/users#index
                     POST   /admin/users(.:format)            admin/users#create
      new_admin_user GET    /admin/users/new(.:format)        admin/users#new
     edit_admin_user GET    /admin/users/:id/edit(.:format)   admin/users#edit
          admin_user GET    /admin/users/:id(.:format)        admin/users#show
                     PUT    /admin/users/:id(.:format)        admin/users#update
                     DELETE /admin/users/:id(.:format)        admin/users#destroy

Which is what we want right? Now my question is, what is the naming convention for the functions in the admin controller?

How do I name my functions so they correspond to the following paths? I place the functions in the user controller or the admin?

I'm getting a routing error

uninitialized constant Admin

I don't think I've gotten the hang of routing just yet. Any additional resources would also be much appreciated.

I've been looking at http://guides.rubyonrails.org/routing.html#controller-namespaces-and-routing with not much success though. Thanks a lot!

1 Answer 1

3

Here is a typical setup for namespaced controllers (pay careful attention to the inheritance):

# app/controllers/admin/base_controller.rb:
class Admin::BaseController < ApplicationController
end

# app/controllers/admin/users_controller.rb:
class Admin::UsersController < Admin::BaseController
  # here, you can define all of the methods shown by 'rake routes':
  def index
    # ...
  end

  def show
    # ...
  end

  # etc...
end

The Admin::BaseController provides a nice top-level class for the admin namespace, similar to how the ApplicationController relates to the rest of your controllers. You can throw a before_filter in here to authorize admin users only, which will be called before any method from classes that inherit from the base controller.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. I was testing your code and I got carried away and forgot to thank you hehe.
I have another question! Now when I go to the url /admin/users/new it's pointing the new function inside the user controller. I tried restarting the server to no avail. Hmm. Any thoughts?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.