David
David

Reputation: 825

Devise - creating users only by admin

I'm creating an app where I need only admins to create new users:

routes.rb:

devise_for :users, :skip => [:registrations]
resources :users
root 'dashboard#index'

users_controller.rb

# GET /users/1/edit
#def edit
#  
#end

# POST /users
# POST /users.json
def create

  build_resource(sign_up_params)


  respond_to do |format|
    if resource.save

      format.html { redirect_to user_path(resource), notice: 'User was successfully created.' }
      format.json { render :show, status: :created, location: user }
    else
      clean_up_passwords resource
      respond_with resource
    end
  end

end

When I open http://localhost:3000/users/new

I got this error:

AbstractController::ActionNotFound at /users/new
Could not find devise mapping for path "/users/new".
This may happen for two reasons:

1) You forgot to wrap your route inside the scope block. For example:

  devise_scope :user do
    get "/some/route" => "some_devise_controller"
  end

2) You are testing a Devise controller bypassing the router.
   If so, you can explicitly tell Devise which mapping to use:

   @request.env["devise.mapping"] = Devise.mappings[:user]

What is wrong there? Thank you a lot!

Upvotes: 3

Views: 890

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

The problem is that you're confusing Devise functionality with that of your app:

#config/routes.rb
resources :users #-> nothing to do with devise

When you create a user, you're using the devise build_resource helper. Problem being that this will require devise functionality, which is not going to happen for users_controller.

To use sign_up_params or build_resource, you'll have to scope your routes to a devise controller (so all the available session data is there)...

#config/routes.rb
devise_for :user, skip: [:registrations]
devise_scope :user do
   resources :users, path: "", only: [:new, :create], controller: "registrations" #-> url.com/users/new
end

This way, you'll be able to override the standard Devise::RegistrationsController with your own code:

#app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
   before_action :authenticate_user!
   before_action :check_admin

   def create
      build_resource(sign_up_params)
      ...
   end

   private

   def check_admin
      redirect_to root_path unless current_user.admin?
   end
end

--

What I would recommend is either removing the Devise functionality from your users controller, or overriding the registrations controller so that only an admin can create a user (which it seems you're trying to do already).

Upvotes: 2

Related Questions