Sunday, March 18, 2018

Devise redirect back on sign up failure with validations

Leave a Comment

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.

2 Answers

Answers 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.

Answers 2

A possible solution can be to move your sign_up code to a separate layout file. Make sure you include the <html> and title tags in your file.

Generate Devise controllers using

rails generate devise:controllers users 

In your routes:

devise :users, controllers: { registrations: "users/registrations" } 

Then, render your custom layout in the Devise controller you just generated.

class Users::RegistrationController < Devise::RegistrationsController   layout "new_registration", only: [:new, :create] end 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment