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 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,
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.
You can simply add this method to your application controller:
def after_sign_in_path_for(resource) user_path(current_user) # your path
end 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
endWhere 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
endAlso, 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
endAnd 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
endThat's all.
I hope this helps
You can use the below code in the application controller or any controller where you need to do the operation:
def after_sign_in_path_for(resource) users_path
end I used example 1:
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :authenticate_user! protected def after_sign_in_path_for(resource) current_user.is_a?(Admin) ? admin_tests_path : (stored_location_for(resource) || root_path) end
end Here's what I believe is the answer you are looking for from the devise wiki:
How To: Change the default sign_in and sign_out routes
1