Ruby on Rails: How do you get the previous URL?
Ruby on-RailsRuby on-Rails Problem Overview
How to get the previous URL in Rails? Not the URL that you got a request from, but the one before that?
Because I'm getting an AJAX request, and I need the URL for the page they are currently on (or the URL before the AJAX).
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
Try to use HTTP_REFERER
.
In Rails: request.referrer
or request.headers["HTTP_REFERER"]
Solution 2 - Ruby on-Rails
Use
<%= url_for(:back) %>
# if request.env["HTTP_REFERER"] is set to "http://www.example.com"
# => http://www.example.com
Solution 3 - Ruby on-Rails
In a web application there is no such thing as a previous url. The http protocol is stateless, so each request is independent of each other.
You could have the Javascript code, that sends a request back, send the current url with the request.
Solution 4 - Ruby on-Rails
Just came across this question and it related to something simple I was doing presently.
A simple solution I have employed before when using ajax wizard style apps is to store two session variables which contain the previous and current request (with all params). I just add these two lines to my application controller
session[:previous_request_url] = session[:current_request_url]
session[:current_request_url] = request.url
Solution 5 - Ruby on-Rails
http://railscasts.com/episodes/246-ajax-history-state -> great for ajax
http://ethilien.net/archives/better-redirects-in-rails/ -> You could put in session as many previous url as you want.