如何在Ruby on Rails视图中获得当前的绝对URL ?
请求。request_uri只返回相对URL。
如何在Ruby on Rails视图中获得当前的绝对URL ?
请求。request_uri只返回相对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
其他回答
对于rails 3:
request.fullpath
如果您所说的相对是指没有域,那么请查看request.domain。
适用于Rails 3.2或Rails 4+
你应该使用request。original_url获取当前URL。在这里找到了当前回购的源代码。
这个方法被记录在original_url方法中,但如果你好奇,它的实现是:
def original_url
base_url + original_fullpath
end
对于Rails 3:
你可以写“#{request.protocol}#{request.host_with_port}#{request. protocol”。Fullpath}",因为请求。Url现在已弃用。
对于Rails 2:
你可以写请求。Url而不是request.request_uri。这结合了协议(通常是主机的http://)和提供完整地址的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
你可以使用:
request.full_path
or
request.url
希望它能解决你的问题。
干杯