4
votes

I am working on an app where a company admin should be able to create and update users in his company. (Users can also create and update their accounts independently).

I used Devise and Cancan for registration and permission management. I configured Devise to get the required signup and user update processes. I created a namespace for the admin views.

My admin controller (/app/controllers/admin/base_controller.rb) looks like this:

class Admin::BaseController < ApplicationController
  authorize_resource :class => false
  layout 'admin'

  def dashboard
  end
end

In addition to my "regular" users_controller, I have a controller (/app/controllers/admin/users_controller.rb) and associated views dedicated to Admin user management.

class Admin::UsersController < Admin::BaseController
  ...
end

Now, what's the cleanest way to implement Devise-related user admin features (at this point, create and update users)?

  1. Have a conditional (based on user permissions) in my "regular" registrations_controller and confirmations_controller to render and redirect different views? (cf. Devise form within a different controller)

  2. Or create new controllers in my admin namespace? If the latest is better, what are the main steps to follow?

1

1 Answers

1
votes

Herein lies your issue, once you namespace or move any user management to another controller, you leave the scope of Devise. So at the point where you are in Admin::UsersController, Devise doesn't care about what you do, there are no 'devise-related' admin features as you stated. You can implement your Admin::UsersController as a standard RESTful controller if you wish.

In this manner, creating users through a namespaced controller, Devise will still perform actions such as confirmations. There is one small thing to keep in mind when creating and updating users this way. If you do not set a password as the admin, you will have to delete the password and password_confirmation from the params hash. To do so, the start of your create and update actions would look like so:

if params[:user][:password].blank?
  params[:user].delete(:password)
  params[:user].delete(:password_confirmation)
end

I employ this same method in many of my applications, and have yet to have it fail.

EDIT

namespace :admin do
  resources :users
end