Rails not redirecting after login
-
13-12-2019 - |
Question
I am learning rails via Hartl's tutorial, but I can get chapter 9.2.3 Link to work
Everything before this section was working perfectly before this section, but after getting here, if I access /users/1/edit and login with a different or same user, it redirects back to the user page and not to the edit page.
sessions helper:
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
session.delete(:return_to)
end
def store_location
session[:return_to] = request.fullpath
end
users controller methods for before_filter
private
def signed_in_user
unless signed_in?
store_location
redirect_to signin_path, notice: "Please sign in."
end
end
def correct_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end
before filters in user controller
before_filter :signed_in_user,only:[:edit,:update,:index]
before_filter :correct_user, only:[:edit,:update]
My code so far Github
Solution
You missed calling redirect_back_or user instead of redirect_to in SessionsController create:
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' # Not quite right!
render 'new'
end
end
I found out by adding the session to the debug info at the bottom of the page, and the return_to was still there after successful login:
{"session_id"=>"4dcc1baaf651aaab953026902b32f805", "_csrf_token"=>"0YkP+yd/DDuInX4kIBkjwbzxV1GK0oYBDAXEiWnHLGs=", "return_to"=>"/users/1/edit"}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow