使用Devise仅允许管理员创建用户

3

我将创建一个应用程序,只允许管理员创建新用户:

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

当我打开 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]

那里出了什么问题?非常感谢!
1个回答

2
问题在于你把Devise的功能和你的应用程序混淆了:
#config/routes.rb
resources :users #-> nothing to do with devise

当你创建一个用户时,你使用的是devise的build_resource帮助程序。问题在于这将需要devise功能,而这不会发生在users_controller中。
要使用sign_up_params或build_resource,你必须将路由范围限定在devise控制器上(以便所有可用的会话数据都在那里)...
#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

这样,您就可以使用自己的代码覆盖标准的Devise :: RegistrationsController
#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

我建议您要么从users控制器中删除Devise功能,要么重写registrations控制器,以便只有管理员才能创建用户(似乎您已经在尝试这样做了)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接