In Rails 4.x,
for going back to previous page we use
However sometimes we get
HTTP_REFERER is not present.
1 2class PostsController < ApplicationController 3 def publish 4 post = Post.find params[:id] 5 post.publish! 6 7 redirect_to :back 8 end 9end 10
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
and redirect to root url.
1 2class PostsController < ApplicationController 3 rescue_from ActionController::RedirectBackError, with: :redirect_to_default 4 5 def publish 6 post = Post.find params[:id] 7 post.publish! 8 redirect_to :back 9 end 10 11 private 12 13 def redirect_to_default 14 redirect_to root_path 15 end 16end 17
Improvement in Rails 5
In Rails 5,
redirect_to :back has been deprecated and instead
a new method has been added
To deal with the situation when
HTTP_REFERER is not present,
it takes required option
1 2class PostsController < ApplicationController 3 4 def publish 5 post = Post.find params[:id] 6 post.publish! 7 8 redirect_back(fallback_location: root_path) 9 end 10end 11
This redirects to
HTTP_REFERER when it is present
HTTP_REFERER is not present then
redirects to whatever is passed as