我正在创建一个应用,我只需要管理员来创建新用户:
devise_for :users, :skip => [:registrations]
resources :users
root 'dashboard#index'
# 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]
那里有什么问题?非常感谢你!
答案 0 :(得分:2)
问题是您的Devise
功能与您应用的功能相混淆:
#config/routes.rb
resources :users #-> nothing to do with devise
当您创建用户时,您正在使用devise
build_resource
帮助程序。问题是这需要设计功能,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
-
我建议您从Devise
控制器中删除users
功能,或覆盖registrations
控制器,以便只有管理员可以创建用户(看起来像你'重新尝试做。)