[英]Devise: Redirect to sign up page instead of sign in if no user exists
如果没有用户在场,我希望将请求重定向到“注册”页面而不是“登录”页面。 因此,我要覆盖authenticate_user!
应用程序控制器中的方法:
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服务器控制台上显示:
Filter chain halted as :authenticate_user! rendered or redirected
Completed 302 Found in 0ms (ActiveRecord: 0.0ms)
对我来说工作也很好,我已经为我和我现有的项目修复了。
在application_controller.rb
上,为每个请求运行并覆盖authenticate_user!
在回调before_action :authenticate_user!
遍布控制器调用此方法也是从SessionsController
和RegistrationsController
时不signed_in
,如果你使用的是在单独的controller
那么一切都OK一样,如果你用这个home_controller.rb
请求时再home_controller.rb
没有sign_in
那么他会参考sign_up
页面。
经过多次搜索,我已修复了以下问题。
在application.rb
我已阻止,我的意思是跳过了before_filter
设计控制器,该控制器可像这样用于login
, logout
和signup
config.to_prepare do
Devise::SessionsController.skip_before_action :authenticate_user!
Devise::RegistrationsController.skip_before_action :authenticate_user!
end
和application_controller.rb
before_action :authenticate_user!
protected
def authenticate_user!
redirect_to new_user_registration_path, notice: 'Your custom message here' unless user_signed_in?
end
而已!
注意
此后,一切正常,但
devise
默认的edit
和updates
无效。
为此,您必须应用解决方案2
解决方案2
devise
默认edit
,如果您删除它, updates
将起作用!
来自authenticate_user
就像下面的application.rb
config.to_prepare do
Devise::SessionsController.skip_before_action :authenticate_user
Devise::RegistrationsController.skip_before_action :authenticate_user
end
和application_controller.rb
before_action :authenticate_user
protected
def authenticate_user
redirect_to new_user_registration_path, notice: 'Your custom message here' unless user_signed_in?
end
如果应用此设置,请确保在编辑application.rb
文件后重新启动服务器。
希望能帮助到你
Devise建议不要覆盖authenticate_user
和authenticate_user!
方法。
而是使用route方法定义一个自定义故障应用程序,该方法将返回表示命名路由的符号以重定向到:
# app/lib/my_failure_app.rb
class MyFailureApp < Devise::FailureApp
def route(scope)
:new_user_registration_url
end
end
然后在Devise初始化程序中,指定您的失败应用程序:
# config/initializers/devise.rb
config.warden do |manager|
manager.failure_app = MyFailureApp
end
如果遇到未初始化的常量CustomFailure错误,并且已将CustomFailure类放在/ lib目录下,请确保将lib文件自动加载到application.rb文件中,如下所示
config.autoload_paths << Rails.root.join('lib')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.