On a rails 2.3.8 site I have login links on each page (that takes a user to a separate signin page). After a successful login the user is currently redirected to root. Instead I'd like to redirect to the page they were previously viewing.
I've 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 that generates an "access denied" error, even though the login is successful.
The most common ways to implement redirection logic after login are: using HTTP Referer header. saving the original request in the session. appending original URL to the redirected login URL.
In Rails 4. x, for going back to previous page we use redirect_to :back. However sometimes we get ActionController::RedirectBackError exception when HTTP_REFERER is not present. This works well when HTTP_REFERER is present and it redirects to previous page.
How do I get the previous URL in Ruby on Rails? In a web application there is no such thing as a previous url. The http protocol is stateless, so each request is independent of each other. You could have the Javascript code, that sends a request back, send the current url with the request.
Before all you must store your url
by cookies
:
cookies[:return_to_url] = request.url
And then after success logging:
redirect_to cookies[:return_to_url] || root_path
cookies[:return_to_url] = nil
# or even better code in one line:
redirect_to cookies[:return_to_url].delete || root_path
https://api.rubyonrails.org/classes/ActionDispatch/Cookies.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With