如何在rails中为url helpers设置默认主机?

gor*_*orn 61 url configuration ruby-on-rails

我想做这样的事情

config.default_host = 'www.subdomain.example.com'
Run Code Online (Sandbox Code Playgroud)

在我的一些配置文件中,object_urlhelpers(ActionView::Helpers::UrlHelper)生成以http://www.subdomain.example.com开头的链接

我试图搜索文档,但除了ActionMailer文档和http://api.rubyonrails.org/classes/Rails/Configuration.html之外我没有找到任何对我没用的东西,因为我不知道在哪个方面看起来.有没有描述Rails :: Initializer.config整个结构的地方?

Wil*_*elm 53

asset_host 不适用于网址

你需要覆盖default_url_options你的ApplicationController(至少在Rails 3中)

http://edgeguides.rubyonrails.org/action_controller_overview.html#default-url-options

class ApplicationController < ActionController::Base
  def default_url_options
    if Rails.env.production?
      {:host => "myproduction.com"}
    else  
      {}
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

  • 或者您可以在您的production.rb#production.rb中设置config.action_controller.default_url_options = {host:'myproduction.com'} (23认同)

And*_*rew 49

在环境配置中定义默认主机:

# config/environments/staging.rb
MyApp::Application.configure do
  # ...
  Rails.application.routes.default_url_options[:host] = 'preview.mydomain.com'
  # ...
end
Run Code Online (Sandbox Code Playgroud)

然后,您可以在应用中的任意位置创建网址:

Rails.application.routes.url_helpers.widgets_url()
Run Code Online (Sandbox Code Playgroud)

或者在您的类中包含URL帮助程序:

class MyLib
  include Rails.application.routes.url_helpers

  def make_a_url
    widgets_url
  end
end
Run Code Online (Sandbox Code Playgroud)

如果未定义默认主机,则需要将其作为选项传递:

widgets_url host: (Rails.env.staging? ? 'preview.mydomain.com' : 'www.mydomain.com')
Run Code Online (Sandbox Code Playgroud)

指定协议之类的东西也很有用:

widgets_url protocol: 'https'
Run Code Online (Sandbox Code Playgroud)

  • 目前它的`Rails.application.default_url_options`,没有.routes (8认同)

gom*_*oma 30

另一种方法是设置它

# config/production.rb
config.action_controller.default_url_options = { host: 'myproduction.com' }
Run Code Online (Sandbox Code Playgroud)

  • 这实际上是唯一对我有用的东西. (4认同)