Ruby-on-rails 在 Rails 中,如何获取当前 url(但没有路径)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5576550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:52:00  来源:igfitidea点击:

In Rails, how to get current url (but no paths)

ruby-on-railsrubyruby-on-rails-3

提问by Martin

If I'm in a URL such as

如果我在一个 URL 中,例如

http://domain.com/mysite/bla

How can I request just the URL with no paths? Such as

如何只请求没有路径的 URL?如

http://domain.com 

回答by fl00r

You can use this

你可以用这个

<%= request.protocol + request.host_with_port %>
#=> https://domain.com:3000
<%= request.protocol + request.host %>
#=> https://domain.com

Starting from Rails 3.2 you can also use

从 Rails 3.2 开始,您还可以使用

<%= request.base_url %>
#=> https://domain.com:3000

回答by Pravin

request.hostshould do the trick, or:

request.host应该可以解决问题,或者:

request.port.blank? ? request.host : "#{request.host}: #{request.port}"

if you need to include the port too.

如果您也需要包含端口。

回答by Ashish

Try this

尝试这个

<%=request.scheme + '://' + request.host_with_port%>

If you want to see all available methods on request object then

如果您想查看请求对象上的所有可用方法,则

<%=request.methods.sort%>

回答by Kulbir Saini

For protocol, domain and port

对于协议、域和端口

<%= "#{request.protocol + request.host}:#{request.port.to_s}" %>

回答by Rohanthewiz

If your port could be anything other than 80 it should be included.

如果您的端口可能不是 80,则应包括在内。

"#{request.protocol}#{request.host_with_port}"

回答by kangkyu

I think this can be useful too, if you're not in a controller.

如果您不在控制器中,我认为这也很有用。

URI.join(url_for(only_path: false), '/').to_s