Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return user to previous page after login (Rails)

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.

like image 809
frostmatthew Avatar asked Feb 28 '12 21:02

frostmatthew


People also ask

How do I redirect a previous URL after login?

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.

How do I redirect back to the page in rails?

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?

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.


1 Answers

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

like image 191
shilovk Avatar answered Sep 27 '22 22:09

shilovk