Rails redirections with new users and logins
- by Kenji Crosland
So I'm trying to get the user to return to the page they were looking at before they click "log in"
This is what I got in my user application controller:
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
And this is what I have in my sessions controller:
def new
@user_session = UserSession.new
session[:return_to] = request.referer
end
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
flash[:notice] = "Login successful!"
redirect_back_or_default(home_path)
else
render :action => :new
end
end
This works fine most of the time but if a user logs in right after they register to the site, they will get redirected to a blank page. I imagine this is the "create" action because it was the last action before going to user sessions new.
So I tried this:
def new
@user_session = UserSession.new
unless request.referer == join_path
session[:return_to] = request.referer
end
end
And this tries to take me back to the login page after I log in.
What I'd really like to do is have the user see their profile when they log in for the very first time.
This wouldn't give me a user id and raised a routing error
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
flash[:notice] = "Login successful!"
redirect_back_or_default(user_path(current_user))
else
render :action => :new
end
end
Anybody gone through these redirecting acrobatics before? I can't seem to get it to work. I'm using authlogic if that helps.