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

请求。request_uri只返回相对URL。


当前回答

这适用于Ruby on Rails 3.0,并且应该被大多数版本的Ruby on Rails支持:

request.env['REQUEST_URI']

其他回答

您可以在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.1.0.rc4中:

 request.fullpath

我认为请求。域名可以,但如果你在像blah.blah.com这样的子目录中呢?这样做是可行的:

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

根据路径结构更改参数。

希望有帮助!

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

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