ruby-on-railshotwire-railsturbo

How do I correctly render images via Hotwire Turbo streams?


My problem: When rendering images using Hotwire/Turbo, all URLs render with host example.org instead of my actual hostname. Regular views are fine, but rendering partials through a Turbo stream leads to ActiveStorage URLs like http://example.org/.../.

Context: I have a simple Todo app, with a working view, partial, and turbo stream which together show a Todo and a list of associated users. When I join a User to a Todo, the turbo stream renders the correct partial, and puts the user's name and avatar in the DOM where I want. However, the image URL from ActiveStorage contains the example.org hostname.

I've set my standard URL options in config/environments/*.rb, including routes.default_url_options[:host], and config.action_mailer.default_url_options[:host]. I also learned about the file config/initializers/application_controller_renderer.rb, where you can set an http_host parameter; however, I've set http_host, the https boolean, and still Turbo is rendering my image_tag with example.org.

Further, I've found limited advice about how to manipulate the default renderer programmatically (in order to fix the issue). This source says to grab ApplicationController.renderer and override the properties, like so:

renderer = ApplicationController.renderer.new(
  http_host: request.host_with_port,
  https: (request.protocol == "https://"),
  "rack.session": request.session
)

but the broadcast_action_to methods do not appear to accept a renderer parameter, so this doesn't actually help me within Turbo.

There must be a configuration that I'm missing, but I'm not finding it in the Turbo or Hotwire documentation.


Solution

  • I was missing config.action_controller.default_url_options. Once I configured that the same as the other default_url_options, my links began to render properly.