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
应该适合你: http : host_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.
you can get full uri ( http://localhost:3000/ or http://my.application.com/ etc) with request_uri
http://apidock.com/rails/ActionController/AbstractRequest/request_uri
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.