简体   繁体   中英

Devise redirects to /users on a failed sign_up or sign_in

Running

  • Rails 6.0.2.2
  • Ruby 2.6.5
  • Devise 4.7.1

Currently in the early stages of setting up a project. I'm using Devise for user authentication, and when a user fails the Sign Up or Sign In process, they get automatically redirected to /users where the error message is shown, which causes a No route matches [GET] "/users" screen should the user decide to refresh their page for any reason.

How do I prevent this from happening?

# routes.rb

Rails.application.routes.draw do
  devise_for :users

  root to:          'pages#index'
  get 'homepage' => 'pages#homepage'
end
# User Model

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :pwned_password
  validates :email, presence: true
end

Everything else has been untouched from the vanilla rails new setup other than a few views unrelated to Devise itself.

This is actually the typical behavior for a Rails application and very little to do with Devise.

When you are performing a POST request you're posting a form to the collection route in this case /users - with is a non-idempotent action. The response to a POST request is conventionally a redirect to the created resource or the form rendered again with error messages.

You can't actually get to this particular "page" again without sending the exact same POST request. A POST request should not be repeated unless the user submits a form.

If you hit the refresh button in the browser at this point it sends a GET request to the same path which is an idempotent verb and your rails server cannot - and should not respond to this GET request by re-rendering that form with errors as its not the same resource and rails will NOT carry over the parameters from that previous POST request.

This same principle applies to the other non-idempotent HTTP verbs PUT, PATCH and DELETE.

If this really is an issue for your app you can add a JavaScript listener on the window.unload event to warn users before refreshing the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM