-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Redirect to new registration (sign up) path if unauthenticated
By default, Devise's authenticate_user!
filter will redirect unauthenticated users to the login page, i.e. new_user_session_url
.
It's possible to redirect these users to another page, for example the new registration (sign up) page, i.e. new_user_registration_url
.
To do this, define a custom failure app with a route
method that returns a symbol representing the named route to redirect to:
# app/lib/my_failure_app.rb
class MyFailureApp < Devise::FailureApp
def route(scope)
:new_user_registration_url
end
end
Then inside the Devise initializer, specify your failure app:
# config/initializers/devise.rb
config.warden do |manager|
manager.failure_app = MyFailureApp
end
If you’re getting an uninitialized constant CustomFailure error, and you’ve put the CustomFailure class under your /lib directory, make sure to autoload your lib files in your application.rb file, like below
config.autoload_paths << Rails.root.join('lib')
Say your app has both Admin
and User
Devise resources. In that case, you don't want to redirect to a new_admin_registration_url
— in fact, you probably shouldn't have such a route in your app to begin with 😬
To handle this, just check which kind of Devise scope is being processed, and conditionally return a URL based on that:
# app/lib/my_failure_app.rb
class MyFailureApp < Devise::FailureApp
def route(scope)
scope.to_sym == :user ? :new_user_registration_url : super
end
end
Notes:
- This approach is preferable to overriding
authenticate_user!
in your controller because it won't clobber a lot of "behind the scenes" stuff Devise does (such as storing the attempted URL so the user can be redirected after successful sign in). - You need to restart your Rails server after making changes to
my_failure_app.rb
.