简体   繁体   English

如何在 Rails 应用程序中获取主机和端口

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

In a Rails Model, I want to be able to find out the host and port.在 Rails 模型中,我希望能够找出主机和端口。 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/ ?例如,如果我在测试环境中,它会返回http://localhost:3000/ ,如果我在生产环境中,它会返回类似http://my.application.com/东西?

host_with_port应该适合你: httphost_with_port

"#{root_url}"

应该在您的routes.rb中声明

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

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. 您必须通过参数将其提供给模型,因为请求对象仅在控制器中可用。

Other answers provided work in controllers or views but can't provide host name in eg: messaging jobs.提供的其他答案在控制器或视图中工作,但不能在例如:消息传递作业中提供主机名。 Action mailer has it's own configuration for this that you're likely using anyway. Action mailer 有它自己的配置,你可能会使用它。

# Access host from anywhere 
Rails.configuration.action_mailer.default_url_options[:host]

# Defined in development.rb/test.rb/production.rb
config.action_mailer.default_url_options = { host: 'www.example.com' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM