如何在 Ruby on Rails 中获取当前的绝对 URL?
如何在我的 Ruby on Rails 视图中获取当前的绝对 URL?
How can I get the current absolute URL in my Ruby on Rails view?
request.request_uri
只返回相对的 URL.
对于 Rails 3.2 或 Rails 4+
您应该使用 request.original_url
来获取当前 URL.在此处找到当前存储库的源代码.
For Rails 3.2 or Rails 4+
You should use request.original_url
to get the current URL. Source code on current repo found here.
此方法记录在 original_url 方法,但如果你好奇,实现是:
This method is documented at original_url method, but if you're curious, the implementation is:
def original_url
base_url + original_fullpath
end
对于 Rails 3:
您可以编写 "#{request.protocol}#{request.host_with_port}#{request.fullpath}"
,因为 request.url
现在已被弃用.
For Rails 3:
You can write "#{request.protocol}#{request.host_with_port}#{request.fullpath}"
, since request.url
is now deprecated.
您可以编写 request.url
而不是 request.request_uri
.这将协议(通常是 http://)与主机和 request_uri 结合起来为您提供完整地址.
You can write request.url
instead of request.request_uri
. This combines the protocol (usually http://) with the host, and request_uri to give you the full address.