skip to content

When a Rails job builds absolute class links for exported calendar invites, why does class_session_url raise Missing host, and where should the host come from?

level: seniorimportance: should knowfreq 38%

answer

  1. no request, no host
  2. ArgumentError: Missing host to link to!
  3. routes-level default_url_options
  4. controller defaults stay in controllers
  5. protocol falls back to http

basics

~10 s

A job has no request, and Rails.application.routes.url_helpers only knows the routes' own default_url_options, empty by default, so _url helpers raise ArgumentError. Set Rails.application.routes.default_url_options with host and protocol per environment.

solid answer

~40 s

In a controller, `_url` helpers start from the request's host, port and protocol. A job, a rake task or a model method that calls `Rails.application.routes.url_helpers.class_session_url(session)` has no request; the only defaults it sees are the route set's `default_url_options`, which start empty. Without a host Rails raises `ArgumentError`: "Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true". Configure the host once per environment with `Rails.application.routes.default_url_options = { host: ..., protocol: "https" }`; `Rails.application.default_url_options=` is the same setting. Setting `default_url_options` on a controller, or `config.action_controller.default_url_options`, does not help a job: those apply only inside controllers and views. Never pass a request's Host header into the job; take the canonical host from configuration.

code

ruby · 15 lines
ruby
# config/initializers/default_url_options.rb
Rails.application.routes.default_url_options = {
  host: ENV.fetch("APP_HOST"),
  protocol: "https"
}

# app/jobs/export_calendar_job.rb
class ExportCalendarJob < ApplicationJob
  def perform(member)
    urls = Rails.application.routes.url_helpers
    member.class_sessions.map do |s|
      { title: s.title, url: urls.class_session_url(s) }
    end
  end
end

go deeper

for a junior

Recall the Missing host to link to! error and that helpers outside a request need a configured host.

for a middle

Explain the merge order: helper options, request-derived controller options, then the route set's default_url_options.

for a senior

Configure host and protocol per environment at the route-set level, keep request data out of jobs and test the generated links.

for a principal

Own the canonical-host policy across web, jobs, mailers and exports, especially when one app serves several domains.

## The failure The yoga-studio app lets members export their booked classes as an `.ics` calendar file. A background job builds each event and needs an absolute link back to the class: ```ruby class ExportCalendarJob < ApplicationJob def perform(member) helpers = Rails.application.routes.url_helpers member.class_sessions.map { |s| helpers.class_session_url(s) } end end ``` In production this raises: > ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true The same code works in a controller, which is what confuses people. ## Why it works in a controller and not in a job URL generation merges options from several layers: 1. The options passed to the helper (`host:`, `protocol:`, `port:`) win. 2. In a **controller or view**, the controller's `url_options` supply the **request's** host, port and protocol, with the controller's `default_url_options` merged on top. 3. The **route set's** `default_url_options` fill in anything still missing. A job, a rake task, a model or any plain Ruby object has no request, so layer 2 does not exist. Only layer 3 is left, and it starts as an empty hash. With no host anywhere, building a full URL is impossible and Rails raises `ArgumentError`. ## Where each setting applies | Setting | Applies to | |---|---| | `host:` passed to the helper | that one call | | `default_url_options` method in a controller | URLs built in that controller and its views | | `config.action_controller.default_url_options` | all controllers and their views | | `Rails.application.routes.default_url_options` | every caller of the route set, including `url_helpers` in jobs and models | | `config.action_mailer.default_url_options` | mailers | The common mistake is setting the controller value and expecting the job to see it. Controller defaults live on `ActionController::Base`; the job never touches a controller. ## The fix Configure the route set once per environment, from configuration rather than code: ```ruby # config/initializers/default_url_options.rb Rails.application.routes.default_url_options = { host: ENV.fetch("APP_HOST"), protocol: "https" } ``` Points to get right: - **Protocol.** Without `protocol:`, generation falls back to `http`, so invite links would start with `http://` and depend on a redirect. Set `https` explicitly in production. - **Port.** Development usually needs `port: 3000` (or a host string that includes it) so links open locally. - **One source of truth.** `Rails.application.default_url_options=` is delegated to the same route-set hash, so there is no second place to keep in sync. - **Tests.** Set the same option in the test environment, or calendar specs fail with the same error. ## What not to do - **Do not pass `request.host` into the job.** It couples the job to whichever host header a visitor sent, which may not be the canonical domain and should never be trusted for links you store or send. - **Do not include `Rails.application.routes.url_helpers` into a model to build links on the fly.** It works, but it drags routing into the domain layer; prefer building URLs in the job or a small presenter that calls `url_helpers` explicitly. - **Do not hard-code the host into string concatenation**; it ignores the configured protocol and port and drifts between environments. - **Do not reach for `only_path: true` to silence the error.** It does stop the exception, but the invite then carries a relative path, which a calendar app cannot open. ## Testing the configuration A missing or wrong host is an environment problem, so pin it with a test that checks the generated value, not just that the job runs: ```ruby test "calendar export links are absolute https URLs" do urls = ExportCalendarJob.perform_now(members(:priya)).map { _1[:url] } assert urls.all? { _1.start_with?("https://") } end ``` Set the test environment’s route-level host the same way as production (with a test host value), so the test exercises the same code path. If the suite only asserts paths, the first person to notice a missing production host will be a member whose calendar link does not open. ## A quick check In a console session for the target environment, `Rails.application.routes.url_helpers.class_session_url(ClassSession.first)` should print the full production URL with `https`. If it raises, the configuration is missing; if it prints `http`, the protocol is.

  • Why does setting config.action_controller.default_url_options not fix Missing host in a Rails job?
    That setting assigns `ActionController::Base.default_url_options`, which only controllers and the views they render read. A job calling `Rails.application.routes.url_helpers` goes straight to the route set, whose own `default_url_options` is still empty. Set `Rails.application.routes.default_url_options` instead, or pass `host:` explicitly.
  • Why should a Rails job not receive request.host to build calendar invite links?
    The Host header is whatever the client sent, so it may be an alias, a staging name or a forged value, and the invite stores it permanently. Links that leave the app should use one canonical host from configuration, so every invite points at the real site regardless of how the request arrived.

  • Setting default_url_options in ApplicationController also covers background jobs
  • Outside a request Rails uses the first entry of config.hosts as the host
  • Passing only_path: true is a fine fix for invite links
  • Without a protocol option, _url helpers default to https in production
  • Rails.application.default_url_options is a separate setting from the routes' hash