【问题标题】:How do I use Devise and ActiveAdmin for the same User model?如何将 Devise 和 ActiveAdmin 用于相同的用户模型?
【发布时间】:2015-05-15 00:39:41
【问题描述】:

我有 ActiveAdmin 和 Devise 与用户合作。我想使用 Devise 登录具有相同用户模型的常规非管理员用户。我怎样才能做到这一点? (我想在 User 模型中有一个 admin 标志,仅供管理员使用。)我尝试将第二行添加到 routes.rb

devise_for :users, ActiveAdmin::Devise.config
devise_for :users

但是当我尝试列出路线时它给出了错误

>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 来说工作正常。 https://github.com/activeadmin/activeadmin/blob/master/docs/13-authorization-adapter.md

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 devise activeadmin


    【解决方案1】:

    我找到了这个http://dan.doezema.com/2012/02/how-to-implement-a-single-user-model-with-rails-activeadmin-and-devise/

    但我最终这样做了

    设计 3.4.1
    ActiveAdmin 1.0.0.pre1
    导轨 4.2.1

    routes.rb
      devise_for :admin_users, {class_name: 'User'}.merge(ActiveAdmin::Devise.config)
      ActiveAdmin.routes(self)
    
      devise_for :users
      resources :users
    
    application_controller.rb
      def access_denied(exception)
        redirect_to root_path, alert: exception.message
      end
    
    config/initializers/active_admin.rb
    config.authorization_adapter = ActiveAdminAdapter
    config.on_unauthorized_access = :access_denied
    

    (并将所有方法从 _user 更改为 admin_user。)

    app/models/active_admin_adapter.rb
    class ActiveAdminAdapter < ActiveAdmin::AuthorizationAdapter
      def authorized?(action, subject = nil)
        user.admin == true
      end
    end
    

    rails generate migration add_admin_to_users admin:boolean
    

    【讨论】:

    • 很棒的答案.. 真的很有帮助。
    • 非常感谢,刚刚登录到upvote :) 也感谢您提供的链接。
    • 如果 admin_users 和 users 有不同的表,这并不能解决问题。设计不会让您在未登录用户的情况下登录管理员。
    • 对上面代码的一些解释将帮助我以我的方式配置 ActiveAdmin。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多