How to Redirect Users Back in Rails

Posted on August 20, 2007
Redirecting users back in Rails should be as simple as:
redirect_to :back

See this ticket for more on a related patch applied to rails in early 2006.

The problem with Rails’ default handing of redirect_to :back is that it throws an exception when the HTTP referrer field has not been set by a visiting browser (or bot).

To be fair—this is probably the most desirable default behavior, given the circumstances.

One solution is simple, to write a wrapper method that you can call from your controllers that does the same thing, only with nil check on request.env[“HTTP_REFERER”]. Place this in your application.rb file (protected method):
def redirect_back(redirect_opts = nil)
  redirect_opts ||= {:controller => 'dashboard'}
  request.env["HTTP_REFERER"] ? redirect_to(request.env["HTTP_REFERER"]) : redirect_to(redirect_opts)
end

Replace “{:controller => ‘dashboard’}” of course with the desired default controller/action/etc for your app.

Google Food

This is the error message Rails throws when the HTTP_REFERER environment variable has not been passed by the browser (perhaps as a result of copy & pasting a URL instead of clicking on it directly):

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”].

Hope this helps!