首页 文章

注册失败时,如何将用户重定向到特定页面?

提问于
浏览
0

我有一个Rails应用程序,它使用Devise进行用户注册/身份验证 . 注册表单和登录表单都是我域的根目录 .

当用户注册失败时(例如,因为他们输入已经采用的电子邮件地址),默认情况下,Devise会重定向到 /users .

我怎么能改变呢?我希望用户被定向到 /

我已成功实现此尝试失败登录尝试,具有以下代码:

class CustomFailure < Devise::FailureApp
  def redirect_url
    "/"
  end

  def respond
    if http_auth?
      http_auth
    else
      redirect
    end
  end
end

和:

config.warden do |manager|
  manager.failure_app = CustomFailure
end

详见on the project's homepage .

有没有办法扩展/改变这个,以便失败的注册也重定向到我的域的根?

我使用的是Ruby 2.2.0,Rails 4.2.0和Devise 3.4.1 .

2 回答

  • 1

    您可能需要子类 Devise::RegistrationsController 并覆盖create动作 . 只需从here复制create方法,并在失败时修改重定向以保存 .

    # app/controllers/registrations_controller.rb
    class RegistrationsController < Devise::RegistrationsController
    
    
      def create
        build_resource
        if resource.save     
            set_flash_message :notice, :inactive_signed_up, :reason => inactive_reason(resource) if is_navigational_format?
            expire_session_data_after_sign_in!
            respond_with resource, :location => after_inactive_sign_up_path_for(resource)
          #end
        else
          clean_up_passwords(resource)
          respond_with_navigational(resource) { render_with_scope :new }
        end
      end
    
    
        end 
    
    # The path used after sign up for inactive accounts. You need to overwrite
    # this method in your own RegistrationsController.
    def after_inactive_sign_up_path_for(resource)
      new_user_session_path
    end
    

    更改路线以告知Devise使用您的控制器:

    # config/routes.rb
    devise_for :users, :controllers => {:registrations => "registrations"}
    
  • 1

    我相信你可以看看this问题 . 您可以覆盖Devise RegistrationsController,并在未保存用户时将 redirect_to 方法添加到 else .

    例如:

    # app/controllers/registrations_controller.rb
    class RegistrationsController < Devise::RegistrationsController
      def new
        super
      end
    
      def create
        if @user.save?
          #something
        else
          redirect_to your_path, error: 'Registration failed'
      end
    

相关问题