在哪里为Rails.application.routes.url_helpers设置主机

pmi*_*hna 12 ruby-on-rails

在控制器中,我称之为服务:

MyService.call
Run Code Online (Sandbox Code Playgroud)

MyService.call方法中我想使用url帮助器:

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

但是,我收到错误:

Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
Run Code Online (Sandbox Code Playgroud)

在config/environments/development.rb我有:

config.action_mailer.default_url_options = { host: 'localhost:3000' }
config.action_controller.default_url_options = { host: 'localhost:3000' }
Run Code Online (Sandbox Code Playgroud)

我该怎么设置不得错误?

Nob*_*ita 11

您可以将配置文件中的主机设置为:

Rails.application.routes.default_url_options[:host] = 'your_host'

这将设置默认主机不只是for action_maileraction_controller,而是用于任何使用url_helpers.

  • 您是否参考了提及此文档的文档?我经常为`action_mailer`找到引用而不是其余的引用 (6认同)
  • 你把这个放在哪个文件里?有几十个“配置文件”。 (5认同)

kma*_*ana 5

根据这一线索,利用航线助手时,他们没有延迟default_url_optionsActionMailerActionController配置,预计将有一个default_url_options在类方法。这对我有用:

class MyService
  include Rails.application.routes.url_helpers

  def call
    something_url
  end

  class << self
    def default_url_options
      Rails.application.config.action_mailer.default_url_options
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

请注意,您可以使用action_maileraction_controller配置,具体取决于配置的对象。