Saturday, April 30, 2011

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

Hi there,

I'm having a problem with redirect_to :back. Yes, it's referrers.

I often get the exception (ActionController::RedirectBackError) "No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env[\"HTTP_REFERER\"]."

I realise that this is a result of a referrer not being available. Is there a way that, for example, one can set a session variable on each access with the last page visited, and, when HTTP_REFERER is not available, utilize this session variable to redirect to?

Thanks!

From stackoverflow
  • def store_location
      session[:return_to] = request.request_uri
    end
    
    def redirect_back_or_default(default)
      redirect_to(session[:return_to] || default)
      session[:return_to] = nil
    end
    

    Try that! (Thanks to the Authlogic plugin)

    : rock! that's awesome. thank you!
    Maran : You are welcome :)
  • 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 :back
    rescue ActionController::RedirectBackError
      redirect_to root_path
    end
    

    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 is this sensible.

    Toby Hede : +1 because this is what I was going to say
    Bob Aman : I suspect that I would alter this to use rescue_from instead.
    harm : That is indeed a very good suggestion!

0 comments:

Post a Comment