Rails 5 improves redirect_to :back method

Abhishek Jain

By Abhishek Jain

on February 29, 2016

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.

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 rescue 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 called redirect_back.

To deal with the situation when HTTP_REFERER is not present, it takes required option fallback_location.

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 and when HTTP_REFERER is not present then redirects to whatever is passed as fallback_location.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.