如何在Ruby on Rails视图中获得当前的绝对URL ?

请求。request_uri只返回相对URL。


当前回答

您可以在ApplicationController中添加这个current_url方法来返回当前URL,并允许合并其他参数

# 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

使用示例:

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

其他回答

Rails 4.0

你可以使用request。Original_url,输出将如下示例所示

get "/articles?page=2"

request.original_url # => "http://www.example.com/articles?page=2"

Rails 4

控制器:

def absolute_url
  request.base_url + request.original_fullpath
end

4.2版中显著的变化:

link_to和url_for在模板中默认生成绝对url,不再需要传递only_path: false。(提交)

观点:

如果使用_url后缀,则生成的URL是绝对的。使用路径获取相对URL。

<%= link_to "Home", root_url %>

欲知详情,请浏览:

http://blog.grepruby.com/2015/04/absolute-url-full-url-in-rails-4.html

如果你使用的是Rails 3.2或Rails 4,你应该使用request。original_url获取当前URL。


该方法的文档在http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url,但如果你好奇,它的实现是:

def original_url
  base_url + original_fullpath
end

编辑:这仍然是Rails 7 (Docs)的情况。

你可以用

request.original_url 

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

获取当前URL。

我需要应用程序URL,但带有子目录。我使用:

root_url(:only_path => false)