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

请求。request_uri只返回相对URL。


当前回答

(url_for(:only_path => false) == "/" )? root_url : url_for(:only_path => false)

其他回答

获取不带任何查询参数的请求URL。

def current_url_without_parameters
  request.base_url + request.path
end

如果你使用的是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)的情况。

对于rails 3:

request.fullpath

如果你想要更具体,也就是说,你知道你需要的路径:

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

Rails 4.0

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

get "/articles?page=2"

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