Ruby-on-rails 如何在 Rails 应用程序中获取主机和端口
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2813290/
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
How do I get the host and port in a Rails application
提问by Jonathan
In a Rails Model, I want to be able to find out the host and port. For example, if I am in a test environment it would return http://localhost:3000/and if I was in production it would return something like http://my.application.com/?
在 Rails 模型中,我希望能够找出主机和端口。例如,如果我在测试环境中它会返回http://localhost:3000/,如果我在生产环境中它会返回类似http://my.application.com/?
回答by Kamilski81
"#{root_url}"
which should be declared in your routes.rb
应该在你的 routes.rb 中声明
回答by yiwen
host_with_portshould work for you:
http://apidock.com/rails/ActionDispatch/Http/URL/host_with_port
host_with_port应该适合你:http:
//apidock.com/rails/ActionDispatch/Http/URL/host_with_port
回答by Rakesh
You can use this
你可以用这个
<%= request.protocol + request.host_with_port %>
#=> https://example.com:3000
<%= request.protocol + request.host %>
#=> https://example.com
When you use in string concatenation
当您在字符串连接中使用时
"#{request.protocol}#{request.host_with_port}/book/1"
# https://example.com:3000/book/1
回答by Maxem
You can get those values in your controllers (request.host, request.port etc.).
您可以在控制器中获取这些值(request.host、request.port 等)。
You'd have to give that to your models via parameters as the request object is only available in the controllers.
您必须通过参数将其提供给您的模型,因为请求对象仅在控制器中可用。
回答by fl00r
you can get full uri (http://localhost:3000/or http://my.application.com/etc) with request_uri
您可以获得完整的 uri(http://localhost:3000/或http://my.application.com/等)request_uri
http://apidock.com/rails/ActionController/AbstractRequest/request_uri
http://apidock.com/rails/ActionController/AbstractRequest/request_uri

