如何在Ruby on Rails视图中获得当前的绝对URL ?
请求。request_uri只返回相对URL。
如何在Ruby on Rails视图中获得当前的绝对URL ?
请求。request_uri只返回相对URL。
当前回答
Rails 4.0
你可以使用request。Original_url,输出将如下示例所示
get "/articles?page=2"
request.original_url # => "http://www.example.com/articles?page=2"
其他回答
你可以使用:
request.full_path
or
request.url
希望它能解决你的问题。
干杯
我需要应用程序URL,但带有子目录。我使用:
root_url(:only_path => false)
您可以在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 3.2或Rails 4 通过这种方式获取request。original_url 参考:原始URL方法
For Rails 3 请求。Url已弃用。我们可以通过连接得到绝对路径
"#{request.protocol}#{request.host_with_port}#{request.fullpath}"
For Rails 2
request.url
这适用于Ruby on Rails 3.0,并且应该被大多数版本的Ruby on Rails支持:
request.env['REQUEST_URI']