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

时间:2018-02-09 09:21:10

标签: ruby-on-rails redirect devise ruby-on-rails-5

如果没有用户在场,我希望将请求重定向到“注册”页面而不是“登录”页面。因此,我正在覆盖应用程序控制器中的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)

2 个答案:

答案 0 :(得分:0)

对我而言,我已经为我和我现有的项目做好了准备。

在每个请求的application_controller.rb运行中以及覆盖authenticate_user!之后以及在回调before_action :authenticate_user!之后,调用此方法的控制器也来自SessionsControllerRegistrationsController如果不是signed_in,那么如果您在单独的controller上使用它,那么一切都很好,就像您将home_controller.rb用于home_controller.rb然后请求sign_in而不是sign_up那样他将参考application.rb页面。

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

before_filter我已屏蔽,我的意思是跳过了login设计控制器,这些控制器适用于logoutsignupconfig.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默认updatesdevise无效。

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

解决方案2

如果您从edit

中移除此updates,则

!默认authenticate_userapplication.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

如果您应用此选项,请确保在编辑const crypto = require('crypto'); var length = 22 var generated = crypto.randomBytes(Math.ceil(length / 2)) .toString('hex').slice(0, length); //it returned "14cf777d3ca307f5e78496" 文件

后重新启动服务器

希望有所帮助

答案 1 :(得分:0)

Devise建议不要覆盖authenticate_userauthenticate_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') 

请参见https://github.com/plataformatec/devise/wiki/Redirect-to-new-registration-(sign-up)-path-if-unauthenticated