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

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

How do I get the host and port in a Rails application

ruby-on-rails

提问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 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.

您必须通过参数将其提供给您的模型,因为请求对象仅在控制器中可用。