ChatGPT解决这个技术问题 Extra ChatGPT

How do I get the current absolute URL in Ruby on Rails?

How can I get the current absolute URL in my Ruby on Rails view?

The request.request_uri only returns the relative URL.


1
15 revs, 15 users 33%

For Rails 3.2 or Rails 4+

You should use request.original_url to get the current URL. Source code on current repo found here.

This method is documented at original_url method, but if you're curious, the implementation is:

def original_url
  base_url + original_fullpath
end

For Rails 3:

You can write "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

For Rails 2:

You can write request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address.


as other users pointed: DEPRECATION WARNING: Using #request_uri is deprecated. Use fullpath instead
@giladbu fullpath does NOT include the protocol/domain/port! It’s not an absolute URL!
"http://#{request.host+request.fullpath}" will work or otherwise, (if the port is important) "http://#{request.host}:#{request.port+request.fullpath}"
if port important, this one works right: "http://#{request.host}:#{request.port}#{request.fullpath}"
Can you point to a reference for the claim that request.url is deprecated? The proposed solution is just a long way of saying what request.url already does; the implementation is simply protocol + host_with_port + fullpath (github.com/rails/rails/blob/…)
P
Peter Mortensen

I think that the Ruby on Rails 3.0 method is now request.fullpath.


fullpath doesn't include the domain
I'm glad this was provided as I was actually searching for how to not include the domain.
g
grzuy

You could use url_for(only_path: false)


In my (a bit special case) this was almost exactly what I wanted. I just changed the option to true and got the url for the current page, without options. Thanks :)
@David not in the View it doesn't. But it should'n be used there anyway =)
In my case I wanted to change host name but keep everything else. I found that url_for(host: 'www.newdomain.com') worked the best for me as a solution to the problem. IMO, its a more robust solution since its the same across all versions of rails.
FYI This will not work if you have multiple paths for the same resource.
For a /activities/:id path I got 404?id=:id when doing url_for(only_path: false) from a page handling "not found", request.original_url works fine
l
lulalala

DEPRECATION WARNING: Using #request_uri is deprecated. Use fullpath instead.


See notes on answer stackoverflow.com/a/2165727/166279, fullpath doesn't include the domain.
this line came straight from the log at time of writing when using request.uri and this has already been pointed out several times in this question, but... ok, thanks
@ManishShrivastava: funny, in spite of all the "original" effort I put answering more complex questions, this copy and paste gave me the highest score, well... better than nothing
d
dsomel21

If you're using Rails 3.2 or Rails 4, you should use request.original_url to get the current URL.

Documentation for the method is at http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url, but if you're curious, the implementation is:

def original_url
  base_url + original_fullpath
end

EDIT: This is still the case for Rails 7 (Docs).


C
Charles

You can add this current_url method in the ApplicationController to return the current URL and allow merging in other parameters

# https://x.com/y/1?page=1 
# + current_url( :page => 3 )
# = https://x.com/y/1?page=3
def current_url(overwrite={})
    url_for :only_path => false, :params => params.merge(overwrite)
end

Example Usage:

current_url --> http://...
current_url(:page=>4) --> http://...&page=4

This does not appear to be defined in Rails 3.1.
you could do it this way url_for params.merge(:format => "PDF", :only_path => false)
also if you are in a link_to you can just use params.merge and skip the url_for altogether
P
Peter Mortensen

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

P
Peter Mortensen

In Ruby on Rails 3.1.0.rc4:

 request.fullpath

fullpath does not provide an absolute URL as the original poster requested.
P
Peter Mortensen

I needed the application URL but with the subdirectory. I used:

root_url(:only_path => false)

P
Peter Mortensen
 url_for(params)

And you can easily add some new parameter:

url_for(params.merge(:tag => "lol"))

This is far more elegant (if less granular) than the approved answer.
J
James M

I think request.domain would work, but what if you're in a sub directory like blah.blah.com? Something like this could work:

<%= request.env["HTTP_HOST"] + page = "/" + request.path_parameters['controller'] + "/" + request.path_parameters['action'] %>

Change the parameters based on your path structure.

Hope that helps!


Yes Jaime's answer is way better, but if you want to be really inefficient, you could do it my way.
P
Peter Mortensen

It looks like request_uri is deprecated in Ruby on Rails 3.

Using #request_uri is deprecated. Use fullpath instead.

P
Peter Mortensen

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

Yup, fullpath gets you the url you requested, not the url you came from, which is what I needed as well. Thanks for this!
Works great, just what I needed. This should be in a seperate question and answer though. Kinda hard to find here. :/
P
Peter Mortensen

This works for Ruby on Rails 3.0 and should be supported by most versions of Ruby on Rails:

request.env['REQUEST_URI']

F
Frans

None of the suggestions here in the thread helped me sadly, except the one where someone said he used the debugger to find what he looked for.

I've created some custom error pages instead of the standard 404 and 500, but request.url ended in /404 instead of the expected /non-existing-mumbo-jumbo.

What I needed to use was

request.original_url

P
Peter Mortensen

If by relative, you mean just without the domain, then look into request.domain.


J
Jai Chauhan

You can use the ruby method:

:root_url

which will get the full path with base url:

localhost:3000/bla

This is the only solution that works in serializers using active_model_serializers in Rails 4.
Can you please tell me how can I restrict the params I pass to an absolute url when I use somethin like :root_url to get the absolute url ? Assume I'm usin somethin like some_method(:products_brand_url, brand: brand, entity_name: "brand") and some_method is defined as ` def some_method(route, opts = {}) end ` I don't want my route to look like - http://localhost:3000/brands/brand_name?&entity_name="brand". I want the route to look like http://localhost:3000/brands/brand_name. I just want the entity_name to be a part of the opts hash and not as a params to the absolute url.
Certainly there's no Ruby method called root_url.
m
msroot
(url_for(:only_path => false) == "/" )? root_url : url_for(:only_path => false)

m
mikrobi

In Rails 3 you can use

request.original_url

http://apidock.com/rails/v3.2.8/ActionDispatch/Request/original_url


u
uma

you can use any one for rails 3.2:

request.original_url
or
request.env["HTTP_REFERER"]
or
request.env['REQUEST_URI']

I think it will work every where

"#{request.protocol}#{request.host}:#{request.port}#{request.fullpath}"

A
Arvind singh

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"

R
Robin Garg

You can either use

request.original_url 

or

"#{request.protocol}#{request.host_with_port}" 

to get the current URL.


N
Noor Ali Khan

For Rails 3.2 or Rails 4 Simply get in this way "request.original_url" Reference: Original URL Method

For Rails 3 As request.url is deprecated.We can get absolute path by concatenating

"#{request.protocol}#{request.host_with_port}#{request.fullpath}"

For Rails 2

request.url

V
Victor S

if you want to be specific, meaning, you know the path you need:

link_to current_path(@resource, :only_path => false), current_path(@resource)

P
Pankhuri

For rails 3 :

request.fullpath


S
Satishakumar Awati
request.env["REQUEST_URI"]

works in rails 2.3.4 tested and do not know about other versions.


N
Nerve

To get the request URL without any query parameters.

def current_url_without_parameters
  request.base_url + request.path
end

A
Artem Mostyaev

You can set a variable to URI.parse(current_url), I don't see this proposal here yet and it works for me.


A
Ali Hassan Mirza

You can use:

request.full_path

or

request.url

Hopefully it will resolve your problem.

Cheers


A
Ahmad hamza

To get the absolute URL which means that the from the root it can be displayed like this

<%= link_to 'Edit', edit_user_url(user) %>

The users_url helper generates a URL that includes the protocol and host name. The users_path helper generates only the path portion.

users_url: http://localhost/users
users_path: /users