How can I redirect a user's home (root) path based on their role using Devise?

后端 未结 5 2076
天涯浪人
天涯浪人 2020-12-02 11:18

I\'m working on a project management app, and in the app, I have project_managers and clients. I\'m using Devise and CanCan for authenticat

5条回答
  •  情话喂你
    2020-12-02 12:01

    Your routes.rb file won't have any idea what role the user has, so you won't be able to use it to assign specific root routes.

    What you can do is set up a controller (for example, passthrough_controller.rb) which in turn can read the role and redirect. Something like this:

    # passthrough_controller.rb
    class PassthroughController < ApplicationController
      def index
        path = case current_user.role
          when 'project_manager'
            some_path
          when 'client'
            some_other_path
          else
            # If you want to raise an exception or have a default root for users without roles
        end
    
        redirect_to path     
      end
    end
    
    # routes.rb
    root :to => 'passthrough#index'
    

    This way, all users will have one point of entry, which in turn redirects them to the appropriate controller/action depending on their role.

提交回复
热议问题