How to redirect to previous page in Ruby On Rails?
In your edit action, store the requesting url in the session hash, which is available across multiple requests:
session[:return_to] ||= request.referer
Then redirect to it in your update action, after a successful save:
redirect_to session.delete(:return_to)
Why does redirect_to(:back)
not work for you, why is it a no go?
redirect_to(:back)
works like a charm for me. It's just a short cut for
redirect_to(request.env['HTTP_REFERER'])
http://apidock.com/rails/ActionController/Base/redirect_to (pre Rails 3) or http://apidock.com/rails/ActionController/Redirecting/redirect_to (Rails 3)
Please note that redirect_to(:back)
is being deprecated in Rails 5. You can use
redirect_back(fallback_location: 'something')
instead (see http://blog.bigbinary.com/2016/02/29/rails-5-improves-redirect_to_back-with-redirect-back.html)
I like Jaime's method with one exception, it worked better for me to re-store the referer every time:
def edit
session[:return_to] = request.referer
...
The reason is that if you edit multiple objects, you will always be redirected back to the first URL you stored in the session with Jaime's method. For example, let's say I have objects Apple and Orange. I edit Apple and session[:return_to]
gets set to the referer of that action. When I go to edit Oranges using the same code, session[:return_to]
will not get set because it is already defined. So when I update the Orange, I will get sent to the referer of the previous Apple#edit action.