Rails、活动管理员、设计、路线

Rails, Active Admin, Devise, routes

我一直在使用 Rails、Active Addmin 和 cancancan。除了一件事,一切都很好。最近我为 admin 类型的用户和 clients 添加了单独的名称空间。

在此更改之前,我以这种方式将所有经过身份验证的用户重定向到同一个活动管理仪表板 (routes.rb):

  devise_scope :user do
    authenticated :user do  
        root :to => 'admin/dashboard#index', as: :authenticated_root
    end
    unauthenticated :user do
      root :to => 'pages#index', as: :unauthenticated_root
    end
  end

目前我需要以某种方式添加额外的条件来检查经过身份验证的用户是否具有角色 adminclient

我的想法是做成这样:

devise_scope :user do
    authenticated :user do 
      if current_user.role?(:Architect) || current_user.role?(:Admin) 
        root :to => 'admin/dashboard#index', as: :authenticated_root
      else 
        root :to => 'clients/dashboard#index', as: :authenticated_client
      end
    end
    unauthenticated :user do
      root :to => 'pages#index', as: :unauthenticated_root
    end
  end

但我收到错误消息:未定义的局部变量或方法`current_user' 有人知道如何检查用户在路由中的角色吗?有更好的方法吗?

页面控制器:

class PageController < ApplicationController

  before_filter :check_route, :only => [:index]

  def check_route
    return unless user_signed_in?
    if current_user.role?(:Architect) || current_user.role?(:Admin)
      redirect_to :controller => 'admin/dashboard', :action => 'index'
    else
      redirect_to :controller => 'clients/dashboard', :action => 'index'
    end
  end
end

routes.rb:

root :to => 'pages#index', as: :unauthenticated_root

root 是负责路由定义的配置文件,您不能访问配置文件中的任何会话变量。

如果您想在登录后重定向用户,您可以使用 Devise::SessionsController

中的 after_sign_in_path_for 方法
class SessionsController < Devise::SessionsController

    def after_sign_in_path_for(resource)
        if resource.role?(:Architect) || resource.role?(:Admin) 
            authenticated_root_url
        else
            authenticated_client_url
        end 
    end
end

在您的路线中您需要指明自定义 sessions_controller

devise_for :user, :controllers => {:sessions => "sessions"}