Rails: Redirect after sign in with Devise

后端 未结 6 2019
说谎
说谎 2020-12-14 00:32

Is it possible to redirect users to different pages (based on role) after signing in with Devise? It only seems to redirect to the root :to => ... page defined in routes.rb

6条回答
  •  旧巷少年郎
    2020-12-14 01:21

    Devise has a helper method after_sign_in_path_for which can be used to override the default Devise route to root after login/sign-in.

    To implement a redirect to another path after login, simply add this method to your application controller.

    #class ApplicationController < ActionController::Base
    
    def after_sign_in_path_for(resource)
      users_path
    end
    

    Where users_path is the path that you want it to redirect to, User is the model name that corresponds to the model for Devise.

    Note: If you used Admin as your model name for Devise, then it will be

    #class ApplicationController < ActionController::Base
    
    def after_sign_in_path_for(resource)
      admins_path
    end
    

    Also, if you generated controllers for Devise, then you can define this in the sessions controller, say, your Devise model is Admin, you can define this in the app/controllers/admins/sessions_controller.rb file to route to the dashboard_index_path:

    # app/controllers/admins/sessions_controller.rb'
    
    def after_sign_in_path_for(resource)
      dashboard_index_path
    end
    

    And in the registrations controller - app/controllers/admins/registrations_controller.rb file:

    # app/controllers/admins/registrations_controller.rb
    
    def after_sign_up_path_for(resource)
      dashboard_index_path
    end
    

    That's all.

    I hope this helps

提交回复
热议问题