Return user to previous page after login (Rails)

On the rails 2.3.8 website, I have login links on each page (which leads the user to a separate login page). After a successful login, the user is currently redirected to root. Instead, I would like to redirect to the page they previously viewed.

I tried using request.referer:

redirect_back_or_default(request.referer) 

Where redirect_back_or_default:

 def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end 

But this creates an "access denied" error, even if the login is successfully completed.

+8
ruby-on-rails
source share
1 answer

Instead of redirecting to the referrer, I would establish a session [: return_to]

For all your actions, you will need a before filter, which runs before your authentication:

 def store_return_to session[:return_to] = request.url end 

Then change your redirect to just

 redirect_back_or_default() 
+13
source share

All Articles