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

请求。request_uri只返回相对URL。


当前回答

你可以使用:

request.full_path

or

request.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

看起来在Ruby on Rails 3中request_uri已弃用。

Using #request_uri is deprecated. Use fullpath instead.

如果您所说的相对是指没有域,那么请查看request.domain。

遗憾的是,这篇文章中的建议没有一个对我有帮助,除了有人说他使用调试器来找到他要找的东西。

我已经创建了一些自定义错误页面,而不是标准的404和500,但请求。Url以/404结束,而不是预期的/non- existent -mumbo-jumbo。

我需要用的是

request.original_url

你可以使用ruby方法:

:root_url

它将获得包含base url的完整路径:

localhost:3000/bla