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

Updated . Posted . Visible to the public.
### 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
Tags
Posted by Alexander M to Ruby and RoR knowledge base (2016-03-31 12:41)