3

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.

aidan
  • 1,627
  • 17
  • 27

2 Answers2

6

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.

aidan
  • 1,627
  • 17
  • 27
0

In my case I have a dynamic default_url_options as my application is multi-tenant so I added this to ApplicationController:

def default_url_options
  { host: SiteSetting[:entity].domains.first.name, protocol: 'https' }
end

I think this all springs from having an asset_host configuration in place so that normally image url's have the asset host in them. ActiveStorage url's use the current default host (not the asset host of course) because they're actually redirect routes rather than actual files. I'd assume if asset_host isn't set, then the image paths would be relative and not absolute? It'd be ideal if they could just be kept relative regardless.

Brendon Muir
  • 4,540
  • 2
  • 33
  • 55