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

请求。request_uri只返回相对URL。


当前回答

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

其他回答

这适用于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
(url_for(:only_path => false) == "/" )? root_url : url_for(:only_path => false)

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

你可以使用ruby方法:

:root_url

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

localhost:3000/bla