When using Ruby on Rails, especially Rails 5, you may encounter an error like “Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true”. Here are notes on how to fix this error.
Cause of the Error
This error occurs when a host name is not specified when generating URLs. For example, when generating links in emails, if the host name is not set, Rails doesn’t know which host name to use and displays this error message.
Solutions
-
Provide the :host Parameter
Explicitly specify the :host parameter when generating URLs.
link_to 'Example', example_path(host: 'www.example.com') -
Set default_url_options[:host]
Set a default host name to use throughout the Rails application. This is typically set in
config/environments/development.rborconfig/environments/production.rb.Rails.application.routes.default_url_options[:host] = 'www.example.com' -
Set :only_path to true
Configure to generate only the path without including the host name.
link_to 'Example', example_path(only_path: true)
For more details, also refer to the related Stack Overflow thread.