问题描述
我有ActiveAdmin和Devise与用户一起工作。我想使用Devise登录具有相同用户模型的常规非管理员用户。我怎样才能做到这一点? (我想在用户模型中为仅管理员提供 admin
标志。)我尝试将第二行添加到route.rb
I have ActiveAdmin and Devise working with Users. I would like to use Devise to log in regular non-admin users with the same User model. How can I do this? (I want to have an admin
flag in the User model for only admins.) I tried adding the 2nd line to routes.rb
devise_for :users, ActiveAdmin::Devise.config
devise_for :users
但是当我尝试列出路线时,它给出了一个错误
But it gave an error when I tried to list the routes
>rake routes
DL is deprecated, please use Fiddle
rake aborted!
ArgumentError: Invalid route name, already in use: 'new_user_session'
You may have defined two routes with the same name using the `:as` option, or you may be overriding a route already defined by a resource with the same naming. For the latter, you can restrict the routes created with `resources` as explained here:
http://guides.rubyonrails.org/routing.html#restricting-the-routes-created
我创建了一个授权适配器,该适配器仅检查 user.admin == true
并且对于ActiveAdmin来说运行正常。
I've created an authorization adapter which just checks user.admin == true
and that is working OK for ActiveAdmin. https://github.com/activeadmin/activeadmin/blob/master/docs/13-authorization-adapter.md
推荐答案
我找到了这个
但是我最终还是这样做了
But I ended up doing this
routes.rb
routes.rb
devise_for :admin_users, {class_name: 'User'}.merge(ActiveAdmin::Devise.config)
ActiveAdmin.routes(self)
devise_for :users
resources :users
application_controller.rb
application_controller.rb
def access_denied(exception)
redirect_to root_path, alert: exception.message
end
config / initializers / active_admin .rb
config/initializers/active_admin.rb
config.authorization_adapter = ActiveAdminAdapter
config.on_unauthorized_access = :access_denied
(并将所有方法从 _user
更改为 admin_user
。)
(And changing all methods from _user
to admin_user
.)
class ActiveAdminAdapter < ActiveAdmin::AuthorizationAdapter
def authorized?(action, subject = nil)
user.admin == true
end
end
然后
rails generate migration add_admin_to_users admin:boolean
这篇关于如何将Devise和ActiveAdmin用于同一用户模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!