Devise Redirects to specific page based on User Ro

2019-05-21 02:59发布

问题:

I have three possible permissions for a User to be in my Rails app, they are User.is_admin, User.is_school, and User.is_security. Based on the nature of my app I need to have a separate home screen for each of these users that do radically different things, which I have working. The problem that I'm having has to do with how Devise auto redirects to root_path after login for all users, regardless of the permissions I have set.

I generated the Devise Sessions controllers into the Users namespace and I have overwritten it to default to my controller, but now when I try to do a redirect, based on the conditional permissions, I get a DoubleRenderError (The obvious reason being that Devise is redirecting elsewhere when creating the session).

I have tried running it as an after_action and even tried overwriting the after_sign_in_path_for method, as per the direction of the Devise docs on the matter, but I still can't get it working. Any help would be appreciated, thank you!

回答1:

You can do something like this

class ApplicationController < ActionController::Base
  def after_sign_in_path_for(resource)
    if resource.role == 'admin'
      admin_root_path
    else
      user_root_path
    end
  end
end

you can read more about this https://github.com/plataformatec/devise/wiki/How-To:-redirect-to-a-specific-page-on-successful-sign-in