设计:如果没有用户,则重定向以注册页面而不是登录

如果没有用户在场,我希望将请求重定向到“注册”页面而不是“登录”页面。 所以,为此,我重写了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! 如果你在单独的controller上使用它,那么整个控制器也会从SessionsControllerRegistrationsController调用这个方法,如果你在单独的controller上使用它,那么一切都很好,如果你将它用于home_controller.rb然后在请求home_controller.rb没有sign_in然后他会参考sign_up页面。

经过多次搜索,我已修好如下。

application.rb我已经阻止了我的意思是跳过了before_filter设计控制器,这对于loginlogoutsignup都是这样的

 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默认editupdates不起作用。

为此,您必须应用解决方案2

解决方案2

devise默认editupdates将删除此function! 来自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文件后重新启动服务器

希望能帮助到你