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

### 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
### 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
Alexander M about 6 years ago
This website uses short-lived cookies to improve usability.
Accept or learn more