Return user to previous page after login (Rails)

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


Instead of trying to redirect to the referrer, I would set the session[:return_to]

You'll need a before filter that runs before your authentication on all your actions:

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

Then change your redirect to just be

redirect_back_or_default()