Capturing previous URL

Tagged with Rails

Language: Ruby

A simple way to “go back” to the previous page. Use the session to track the URLs by loading the current URL in each time, and then updating it on each request. If you don’t want a URL to be recorded (you want the user to go back to the page before another page, use the :except option with the filter.

Then just

redirect_to session[:last_request_uri]

View as text

  after_filter :save_last_request_uri

  # saves the last requested uri to the session. Ignores reloads, Ajax requests, and redirects.
  def save_last_request_uri

    if request.get? and response.redirected_to.nil?
      session[:last_request_uri] = session[:this_request_uri]
      session[:this_request_uri] = request.request_uri
      session[:last_unique_request_uri] = session[:last_request_uri] if session[:this_request_uri] != session[:last_request_uri]
    end
  end
Last updated at 21:29 PM on Oct 10, 2008 by Brian Hogan

SnippetStash costs money to host and develop. The service is free for everyone to use
but if you found it useful please consider making a small donation.