我已经在谷歌上搜索了大约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而不是路径。

什么好主意吗?


当前回答

主机应该在每个环境的配置文件中指定。例如:

config/environments/development.rb

看看这个问题和这个问题。

其他回答

主机应该在每个环境的配置文件中指定。例如:

config/environments/development.rb

看看这个问题和这个问题。

我也犯了同样的错误。我正确地编写了所有内容,包括教程中的清单10.13。

Rails.application.configure do
.
.
.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delevery_method :test
host = 'example.com'
config.action_mailer.default_url_options = { host: host }
.
.
.
end

显然,把"example.com"换成了我的服务器url。

我在教程中忽略的是这一行:

重新启动开发服务器以激活配置…

所以对我来说,答案是关闭服务器,然后重新打开。

设置default_url_options以使用action_mailer.default_url_options。

在每个环境文件中(例如:development。rb、生产。Rb等),你可以指定default_url_options用于action_mailer:

config.action_mailer.default_url_options = { host: 'lvh.me', port: '3000' }

然而,这些都没有设置MyApp:Application.default_url_options:

$ MyApp::Application.config.action_mailer.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}

$ MyApp::Application.default_url_options
#=> {}

这就是为什么你在ActionMailer之外的任何地方都会得到这个错误。

您可以设置应用程序的default_url_options,以使用您在适当的环境文件中为action_mailer定义的选项(development。rb、生产。rb,等等)。

为了尽可能保持DRY,请在配置/环境中执行此操作。Rb文件,所以你只需要这样做一次:

# Initialize the rails application
MyApp::Application.initialize!

# Set the default host and port to be the same as Action Mailer.
MyApp::Application.default_url_options = MyApp::Application.config.action_mailer.default_url_options

现在当你启动你的应用程序,你的整个应用程序的default_url_options将匹配你的action_mailer.default_url_options:

$ MyApp::Application.config.action_mailer.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}

$ MyApp::Application.default_url_options
#=> {:host=>"lvh.me", :port=>"3000"}

感谢@pduersteler引导我走上这条路。

你可以在应用程序控制器中设置默认的url选项:

class ApplicationController < ActionController::Base
  def default_url_options
    {:locale => I18n.locale}
  end
end

http://guides.rubyonrails.org/action_controller_overview.html#default_url_options

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

development.rb

Rails.application.configure do
...
end

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

在Rails 6中工作。