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

前端 未结 6 1732

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

相关标签:
6条回答
  • 2020-12-17 08:43

    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
    
    0 讨论(0)
  • 2020-12-17 08:45

    host_with_port should work for you: http://apidock.com/rails/ActionDispatch/Http/URL/host_with_port

    0 讨论(0)
  • 2020-12-17 08:50
    "#{root_url}"
    

    which should be declared in your routes.rb

    0 讨论(0)
  • 2020-12-17 08:50

    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.

    0 讨论(0)
  • 2020-12-17 08:56

    Request.host

    http://api.rubyonrails.org/classes/ActionController/Request.html#M000712

    0 讨论(0)
  • 2020-12-17 09:02

    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

    0 讨论(0)
提交回复
热议问题