简体   繁体   中英

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. 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/ ?

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.).

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.

# 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' }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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