Correctly doing redirect_to :back in Ruby on Rails when referrer is not available Correctly doing redirect_to :back in Ruby on Rails when referrer is not available ruby ruby

Correctly doing redirect_to :back in Ruby on Rails when referrer is not available


It is unlikely that you do have a session and don't have a referrer.

The situation that a referrer is not set isn't that uncommon and I usually rescue that expection:

def some_method  redirect_to :backrescue ActionController::RedirectBackError  redirect_to root_pathend

If you do this often (which I think is a bad idea) you can wrap it in an other method like Maran suggests.

BTW I think that's a bad idea because this makes the userflow ambiguous. Only in the case of a login this is sensible.

UPDATE: As several people pointed out this no longer works with Rails 5.Instead, use redirect_back, this method also supports a fallback. The code then becomes:

def some_method  redirect_back fallback_location: root_pathend


Here's my little redirect_to_back method:

  def redirect_to_back(default = root_url)    if request.env["HTTP_REFERER"].present? and request.env["HTTP_REFERER"] != request.env["REQUEST_URI"]      redirect_to :back    else      redirect_to default    end  end

You can pass an optional url to go somewhere else if http_refferrer is blank.


def store_location  session[:return_to] = request.request_urienddef redirect_back_or_default(default)  redirect_to(session[:return_to] || default)  session[:return_to] = nilend

Try that! (Thanks to the Authlogic plugin)