I'm having a problem with redirect_to :back
. Yes, it's referrers.
I often get the exception
(ActionController::RedirectBackError) "No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env[\"HTTP_REFERER\"]."
I realize that this is a result of a referrer not being available. Is there a way that, for example, one can set a session variable on each access with the last page visited, and, when HTTP_REFERER is not available, utilize this session variable to redirect to?
Recently, I encountered the same issue where either I had to redirect
:back
or to specific page. After going to a lot of solution, I finally found this which is simple and seems to solve the issue:If you want to use
session
details, do it in the else part of the code.It is unlikely that you do have a session and don't have a referrer.
The situation that a referrer is not set isn't that uncommon and I usually rescue that expection:
If you do this often (which I think is a bad idea) you can wrap it in an other method like Maran suggests.
BTW I think that's a bad idea because this makes the userflow ambiguous. Only in the case of a login this is sensible.
UPDATE: As several people pointed out this no longer works with Rails 5. Instead, use
redirect_back
, this method also supports a fallback. The code then becomes:Try that! (Thanks to the Authlogic plugin)
Here's my little redirect_to_back method:
You can pass an optional url to go somewhere else if http_refferrer is blank.
Core feature
redirect_back
is a core feature from Rails 5+, it is available in theActionController::Redirecting
module that is already included inApplicationController::Base
.EDIT : source
similar to @troex's answer, add this to your application controller
then use it in your controller