Devise redirect back on sign up failure with valid

2019-06-26 06:23发布

问题:

I have a simple Devise registration form with the validatable plugin. It mostly works as intended, if the user forgets to enter a first name it redirects them back with a red validation message.

The problem is it redirects to the same path a successful login would have the user go to (i.e. it redirects them to /user and not back to /user/sign_up). If the user then refreshes the page for whatever reason they get a No route matches [GET] "/user" error.

How can I force a redirect to go back to the original /user/sign_up route on a sign up failure? I know I can hack the create action in the registration controller but when I redirect to the proper route I lose the Devise validation messages.


Update

It appears the problem is the way Devise handles respond_with Rails 4 How Overwrite Devise Respond Path Upon Error. It looks like Devise tries to render a create template at /user but I still can't override it.

回答1:

First you can create devise controllers using following command -

rails generate devise:controllers users

Then you have to modify your routes for devise

# config/routes.rb
Rails.application.routes.draw do

  devise_for :users,
         :skip => [:registrations]

  devise_scope :user do
    get "user/sign_up", to: "users/registrations#new", as: :new_user_registration
    post "user/sign_up", to: "users/registrations#create", as: :user_registration
  end

end

Hope it's work.