I am working through the rails tutorial (railstutorial.org) and noticed an issue with the sign in form when a validation occurs. My route for this action is:
match '/signin', to: 'sessions#new'
When a validation occurs the URL for the page switches to /sessions. My controller for sessions looks like this:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email])
if user && user.authenticate(params[:session][:password])
sign_in user
redirect_back_or user
else
flash.now[:error] = "Invalid email/password combination"
render 'new'
end
end
My question is how to have this validated form still appear with the url of /signin. Thank you.
If you want to keep using restful routing (which is the current and long time standard for Rails), you can’t. If you don’t mind deviating from this path you can create some custom routes instead of using the “normal” resource-style routing.
First you have to change your controller and move the sign in actions from the
createmethod to thenewmethod (which is what /signin routes to):This means both the initial GET /signin request and the eventual POST /signin requests will get handled by the same action. If a POST was detected it will try to log in the user and redirect on success. If a GET request was made it will simply render the form as normal.
Then you have to change your login form (app/views/sessions/new.html.erb) to use the signin path instead of the normal route:
That should do it.