How can I get the current absolute URL in my Ruby on Rails view?
The request.request_uri
only returns the relative URL
Rails 4.0
you can use request.original_url
, output will be as given below example
get "/articles?page=2"
request.original_url # => "http://www.example.com/articles?page=2"
I think that the Ruby on Rails 3.0 method is now request.fullpath
.
For rails 3 :
request.fullpath
Using Ruby 1.9.3-p194 and Ruby on Rails 3.2.6:
If request.fullpath doesn't work for you, try request.env["HTTP_REFERER"]
Here's my story below.
I got similar problem with detecting current URL (which is shown in address bar for user in her browser) for cumulative pages which combines information from different controllers, for example, http://localhost:3002/users/1/history/issues
.
The user can switch to different lists of types of issues. All those lists are loaded via Ajax from different controllers/partials (without reloading).
The problem was to set the correct path for the back button in each item of the list so the back button could work correctly both in its own page and in the cumulative page history.
In case I use request.fullpath, it returns the path of last JavaScript request which is definitely not the URL I'm looking for.
So I used request.env["HTTP_REFERER"] which stores the URL of the last reloaded request.
Here's an excerpt from the partial to make a decision
- if request.env["HTTP_REFERER"].to_s.scan("history").length > 0
- back_url = user_history_issue_path(@user, list: "needed_type")
- else
- back_url = user_needed_type_issue_path(@user)
- remote ||= false
=link_to t("static.back"), back_url, :remote => remote
To get the request URL without any query parameters.
def current_url_without_parameters
request.base_url + request.path
end
For Ruby on Rails 3:
request.url
request.host_with_port
I fired up a debugger session and queried the request object:
request.public_methods