Posted over 5 years ago. Visible to the public.

Improve `redirect_to :back` with new `redirect_back` method.

Copy
### Rails 4.x ### class PostsController < ApplicationController # HTTP_REFERER is not present and it throws exception 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
Copy
### Rails 5 ### class PostsController < ApplicationController def publish post = Post.find params[:id] post.publish! # 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 redirect_back(fallback_location: root_path) end end

Owner of this card:

Avatar
Alexander M
Last edit:
over 5 years ago
by Alexander M
Tags:
Rails-5-0
Posted by Alexander M to Ruby and RoR knowledge base
This website uses short-lived cookies to improve usability.
Accept or learn more