我已经在谷歌上搜索了大约90分钟,仍然没有答案。我在哪里设置default_url_options?我已经设置了config.action_mailer.default_url_options来解决其他地方的这个错误,但现在我在尝试使用RSpec规范内的URL helper时得到了这个错误。我不知道它在哪里期望default_url_options被设置。

 Failure/Error: listing_url(listing).should match(/\/\d+-\w+$/)
 RuntimeError:
   Missing host to link to! Please provide :host parameter or set default_url_options[:host]
 # ./spec/routing/listing_routing_spec.rb:9:in `block (3 levels) in <top (required)>'

这段代码与电子邮件/ActionMailer无关,它只是需要一个URL而不是路径。

什么好主意吗?


当前回答

虽然在路由中添加default_url不是正确的解决方案,但它在某些情况下是可行的。

您必须在每个环境(开发、测试、生产)中设置default_url。

你需要做出这些改变。

    config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

 config/environments/test.rb
      config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

  config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

其他回答

Rails.application.routes.default_url_options(主持人):= ' localhost: 3000

在发展中。Rb / test。Rb,可以更简洁如下:

Rails.application.configure do
  # ... other config ...

  routes.default_url_options[:host] = 'localhost:3000'
end

我通过配置环境解决了这个问题。rb作为

YourApp::Application.default_url_options = YourApp::Application.config.action_mailer.default_url_options

你需要为action mailer设置default_url_options针对每个环境,如开发、测试、登台和生产等。

参考:缺少要链接的主机!请提供:host参数或设置default_url_options[:host]

有趣的是,设置config.action_mailer.default_url_options对我没有帮助。此外,在我觉得不属于环境的地方摆弄与环境无关的设置对我来说并不满意。此外,我想要一个解决方案,在sidekiq/resque工人生成url时工作。

到目前为止,我的方法是进入config/environments/{development, production}.rb:

MyApp::Application.configure do
    # Stuff omitted...

    config.action_mailer.default_url_options = {
      # Set things here as usual
    }
end

MyApp::Application.default_url_options = MyApp::Application.config.action_mailer.default_url_options

这适用于我在rails >= 3.2.x。

不想改变其他环境的行为,所以我使用:

development.rb

Rails.application.configure do
...
end

Rails.application.default_url_options = Rails.application.config.action_mailer.default_url_options

在Rails 6中工作。

虽然在路由中添加default_url不是正确的解决方案,但它在某些情况下是可行的。

您必须在每个环境(开发、测试、生产)中设置default_url。

你需要做出这些改变。

    config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

 config/environments/test.rb
      config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'

  config/environments/development.rb
     config.action_mailer.default_url_options = 
      { :host => 'your-host-name' }  #if it is local then 'localhost:3000'