Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to set host for Rails.application.routes.url_helpers

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?

like image 861
pmichna Avatar asked Apr 22 '16 11:04

pmichna


2 Answers

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.

like image 159
Nobita Avatar answered Nov 11 '22 18:11

Nobita


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.

like image 11
kmanzana Avatar answered Nov 11 '22 17:11

kmanzana