【问题标题】:Rails, Active Admin, Devise, routesRails、Active Admin、Devise、路由
【发布时间】:2016-03-24 12:28:07
【问题描述】:

我一直在使用 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' 有人知道我如何检查用户在路线中的角色吗?有没有更好的方法来做到这一点?

【问题讨论】:

  • 您可以在操作过滤器之前检查应用程序控制器中的用户角色。我之前没有访问过routes.rb中的current_user。
  • 这种方法怎么样? stackoverflow.com/questions/31681957/…

标签: ruby-on-rails ruby devise routes cancancan


【解决方案1】:

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

在你的路由中你需要指明自定义的 session_controller

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

【讨论】:

  • 这个对我有用。 Muhammad 的建议也很有价值,但这个解决方案几乎不需要更改代码。 1. 从 routes.rb 我删除了从 devise_scope 开始的整个块... 2. 我添加了:devise_for :users, controllers: {sessions: 'users/sessions', registrations: 'users/registrations', passwords: 'users/passwords'}, path_names: { sign_in: 'login', sign_out: 'logout' }
  • 3.在 /users/sessions_controller.rb 我添加了:def after_sign_in_path_for(resource) if resource.role?(:Architect) || resource.role?(:Admin) admin_dashboard_path else clients_dashboard_path end end
  • @Michal 您还需要在过滤器之前添加,以防用户手动输入网址。
【解决方案2】:

页面控制器:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多