-
Notifications
You must be signed in to change notification settings - Fork 5.5k
How To: Redirect to a specific page on successful sign in, sign up, or sign out
This guide is about redirecting to a specific page. For redirecting to the current page, see How To: Redirect back to current page after sign in, sign out, sign up, update
You can override the default behaviour by creating an after_sign_in_path_for
[RDoc] method in your ApplicationController
and have it return the path for the page you want. There exists a similar method for sign out; after_sign_out_path_for
[RDoc]
class ApplicationController < ActionController::Base
protected
def after_sign_in_path_for(resource)
# return the path based on resource
end
def after_sign_out_path_for(scope)
# return the path based on scope
end
end
Make a new controller "registrations_controller.rb" and customize the appropriate method:
class RegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for(resource)
'/an/example/path' # Or :prefix_to_your_route
end
end
If the account that is registered is confirmable and not active yet, you have to override after_inactive_sign_up_path_for method.
class RegistrationsController < Devise::RegistrationsController
protected
def after_inactive_sign_up_path_for(resource)
'/an/example/path' # Or :prefix_to_your_route
end
end
Finally, you need to make Devise aware of this overridden controller by editing your routes file. if you have:
devise_for :users
It will now become:
devise_for :users, :controllers => {:registrations => "registrations"}
You can see the whole lists of methods to customize on Devise source:
Devise will by default redirect to the root_path. However, if you defined a user_root_path
for your user model (admin_root_path
for an admin model and so on), Devise will use it instead:
match '/welcome' => "welcome#index", as: :user_root
Using Rails 4
get '/welcome' => "welcome#index", as: :user_root
If you want more fine grained control, you can simply override after_sign_in_path_for
:
def after_sign_in_path_for(resource)
stored_location_for(resource) || welcome_path
end
To make the above work, the root path obviously needs to be publicly visible!
If what you really want is to change the way /
redirects for logged-in vs. unauthenticated users, you can use the authenticated
route helper:
authenticated :user do
root to: 'welcome#index', as: :authenticated_root
end
root to: 'landing#index'
As of Rails 4+, two routes with the same name will raise an exception at app load time. In the above example, it is important to note that the two routes respond to the same URL but they have two different route names (authenticated_root_path
and root_path
).