Posted about 6 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