This blog is part of our Rails 5 series.
In Rails 4.x, for going back to previous page we use redirect_to :back.
However sometimes we get ActionController::RedirectBackError exception when
HTTP_REFERER is not present.
class PostsController < ApplicationController
def publish
post = Post.find params[:id]
post.publish!
redirect_to :back
end
end
This works well when HTTP_REFERER is present and it redirects to previous
page.
Issue comes up when HTTP_REFERER is not present and which in turn throws
exception.
To avoid this exception we can use rescue and redirect to root url.
class PostsController < ApplicationController
rescue_from ActionController::RedirectBackError, with: :redirect_to_default
def publish
post = Post.find params[:id]
post.publish!
redirect_to :back
end
private
def redirect_to_default
redirect_to root_path
end
end
In Rails 5, redirect_to :back has been deprecated and instead
a new method has been added called
redirect_back.
To deal with the situation when HTTP_REFERER is not present, it takes required
option fallback_location.
class PostsController < ApplicationController
def publish
post = Post.find params[:id]
post.publish!
redirect_back(fallback_location: root_path)
end
end
This redirects to HTTP_REFERER when it is present and when HTTP_REFERER is
not present then redirects to whatever is passed as fallback_location.

Related blogs
- 01Rails 5 Active Record attributes APIDecember 11, 2018 · Abhay Nikam
- 02Rails 5 Create module and class level variablesSeptember 5, 2016 · Abhishek Jain
- 03Rails 5 silences assets logs in dev mode by defaultSeptember 2, 2016 · Midhun Krishna
- 04Rails 5 disables autoloading while app in productionAugust 29, 2016 · Shailesh Kalamkar