24

In a controller I call a service like:

MyService.call

In the MyService.call method I want to use a url helper:

Rails.application.routes.url_helpers.something_url

However, I get the error:

Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

in config/environments/development.rb I have:

config.action_mailer.default_url_options = { host: 'localhost:3000' }
config.action_controller.default_url_options = { host: 'localhost:3000' }

What should I set not to get the error?

pmichna
  • 4,800
  • 13
  • 53
  • 90
  • Where is 'somewhere in the code'? Perhaps this helps: http://stackoverflow.com/questions/7219732/missing-host-to-link-to-please-provide-host-parameter-or-set-default-url-optio – Nobita Apr 22 '16 at 11:38

2 Answers2

23

You could set the host in the config files as:

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

This will set the default host not just for action_mailer and action_controller, but for anything using the url_helpers.

Nobita
  • 23,519
  • 11
  • 58
  • 87
  • 8
    Do you have a reference to the doc where this is mentionned ? I often find references just for `action_mailer` but not the rest – Cyril Duchon-Doris Apr 23 '17 at 18:35
  • 1
    Seems like this should go in the Rails.application.configure block somewhere? – Tom Rossi May 03 '18 at 21:45
  • 1
    As stated in this answer, much safer to set `routes.default_url_options[:host] = 'your_host'` as opposed to `routes.default_url_options = { host: 'your_host' }`. The latter will blow away any other options that were set. – marksiemers May 14 '18 at 22:01
  • 5
    Which file do you put this in? There are dozens of "config files". – Meekohi Dec 28 '18 at 18:19
  • `config/initializers/routes.rb` would be good place, I think. – jibiel Oct 15 '21 at 10:43
12

According to this thread, whenever using route helpers, they don't defer default_url_options to ActionMailer or ActionController config and it is expected that there will be a default_url_options method in the class. This worked for me:

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

Note that you can use action_mailer or action_controller config depending which you've configured.

kmanzana
  • 1,138
  • 1
  • 13
  • 23