设计:如果没有用户,则重定向到注册页面,而不是登录 [英] Devise: Redirect to sign up page instead of sign in if no user exists
问题描述
如果没有用户在场,我希望将请求重定向到注册页面而不是登录页面。因此,我要覆盖 authenticate_user!
应用程序控制器中的方法:
If no user present, I want a request to be redirected to Sign Up page instead of Login page. So for that, I am overriding the authenticate_user!
the method in Application controller:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
protected
def authenticate_user!
redirect_to new_user_registration_path unless User.any?
end
end
在这里,问题是页面未重定向正确地。该请求将被重定向到注册页面,但无限期,即请求未完成。在Rails服务器控制台上显示:
Here, the issue is the page isn't redirected properly. The request is getting redirected to the sign-up page but indefinitely, i.e. request is not getting completed. On the rails server console it is showing:
Filter chain halted as :authenticate_user! rendered or redirected
Completed 302 Found in 0ms (ActiveRecord: 0.0ms)
推荐答案
Devise不会不建议覆盖 authenticate_user
和 authenticate_user!
Devise does not recommend overriding the authenticate_user
and authenticate_user!
methods.
相反,请使用route方法定义一个自定义失败应用,该方法将返回表示命名路由的符号以重定向到:
Instead, 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
然后在Devise初始化程序中,指定失败的应用程序:
Then inside the Devise initializer, specify your failure app:
# config/initializers/devise.rb
config.warden do |manager|
manager.failure_app = MyFailureApp
end
如果您未初始化持续出现CustomFailure错误,并且已将CustomFailure类放在/ lib目录下,请确保将lib文件自动加载到application.rb文件中,如下所示
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')
请参见 https://github.com/plataformatec/devise/wiki/重定向到新注册(注册)-未经身份验证的路径
这篇关于设计:如果没有用户,则重定向到注册页面,而不是登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!