Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return to previous page after Devise sign in

After a successful login via Devise, how can I redirect the user back to the page they were on?

I've read and searched a lot already, and I understand that I need to define after_sign_in_path_for. I've done this and its working correctly, what I'm having trouble with is understanding how the previous page is stored, and how to call it correctly.

I have this in my sessions controller:

def after_sign_in_path_for(resource)
    return request.env['omniauth.origin'] || session[:user_return_to] || root_path
end

I've also tried

...
return request.env['omniauth.origin'] || stored_location_for(resource) || root_path
...

I don't think I am understanding how to store the location, as the user is redirected back to the root path if they click to log in.

A sign in can be initiated in two ways. Either (a) the user attempts to access a restricted view (i.e. before_filter :authenticate_user!..., in which case they are redirected and prompted to login. Or (b) the user clicks a sign in link which is available on every page if the user is not logged in.

(a) seems to be working. (b) is not. I guess I need to store the current location to session when the user clicks the log in link.

How do I do this? Or, where is a good source of information that would help me understand this.

Thanks!

like image 995
Andy Harvey Avatar asked May 17 '12 06:05

Andy Harvey


2 Answers

You can get the previous url using request.referrer as is explained in this SO question: How to redirect to previous page in Ruby On Rails?

like image 67
Aayush Kumar Avatar answered Oct 04 '22 23:10

Aayush Kumar


Use

redirect_to request.referrer
like image 40
abhas Avatar answered Oct 04 '22 22:10

abhas