---
title: "Rails 5 improves redirect_to :back method"
description:
  "Rails 5 introduces redirect_back method with fallback_location instead of
  using redirect_to:back"
canonical_url: "https://www.bigbinary.com/blog/rails-5-improves-redirect_to_back-with-redirect-back"
markdown_url: "https://www.bigbinary.com/blog/rails-5-improves-redirect_to_back-with-redirect-back.md"
---

# Rails 5 improves redirect_to :back method

Rails 5 introduces redirect_back method with fallback_location instead of using
redirect_to:back

- Author: Abhishek Jain
- Published: February 29, 2016
- Categories: Rails 5, Rails

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.

```ruby

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.

```ruby

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

```

## Improvement in Rails 5

In Rails 5, `redirect_to :back` has been deprecated and instead
[a new method has been added](https://github.com/rails/rails/pull/22506) called
`redirect_back`.

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

```ruby

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`.

## Links

- [Human page](https://www.bigbinary.com/blog/rails-5-improves-redirect_to_back-with-redirect-back)
