Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Devise: redirect after sign in by role

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

like image 311
rsl Avatar asked Oct 03 '11 18:10

rsl


3 Answers

By default Devise does route to root after it's actions. There is a nice article about overriding these actions on the Devise Wiki, https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in

Or you can go even farther by setting stored_locations_for(resource) to nil, and then have different redirects for each action, ie: after_sign_up_path(resource), after_sign_in_path(resource) and so on.

like image 109
janders223 Avatar answered Nov 01 '22 20:11

janders223


You can simply add this method to your application controller:

def after_sign_in_path_for(resource)
  user_path(current_user) # your path
end
like image 32
Asnad Atta Avatar answered Nov 01 '22 19:11

Asnad Atta


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

like image 9
Promise Preston Avatar answered Nov 01 '22 21:11

Promise Preston