Codementor Events

Redirect to back is deprecated in Rails5. What to use instead?

Published Sep 23, 2019

If you have tried to upgrade to Rails 5.1, you would have probably encountered the following error.

undefined method `back_url’

The reason for the error is this line of code in your controller action.

redirect_to :back

Yes, the redirect_to function doesn’t accept :back as an argument in Rails 5. It has been replaced with a newly improved function redirect_back.

redirect_back(fallback_location:"/")
redirect_back(fallback_location: { action: "show", id: 5})
redirect_back(fallback_location: users_path)

Now you might be wondering, what was the need for this change? And, what is the use of fallback_location?

Redirect_to :back is dependent on a request header variable HTTP_REFERER. The HTTP referer is an optional HTTP header field that identifies the address of the webpage (i.e. the URI or IRI) that linked to the resource being requested. If the request was through a direct link then the HTTP_REREFER would be missing in the request header. In such an instance, Rails threw an error. Before Rails 5.1, this had to be explicitly handled through a condition or a rescue block.

Hence, the redirect_back function was introduced. It takes an argument fallback_location, which will be used to redirect the page in case the HTTP_REREFER is missing.Start writing here...

Discover and read more posts from Deekshith H
get started