Default url_options for ActiveStorage

The ActiveStorage tests explicitly state that an exception should be raised if ActiveStorage::Current.url_options is unset.

This is fine and I get why this makes sense for ActiveStorage. What I don’t understand is why ActiveStorage::Current.url_options are not per default set to the details of the current request ({ protocol: request.protocol, host:, port: request.port }) in ActionController::Base of a Rails app so that all controllers have the opportunity to easily generate ActiveStorage URLs.

Can someone explain me the reasoning behind this?

Alternatively if we cannot configure a default url_options, could we at least adjust the rails new generator to include ActiveStorage::SetCurrent in the ApplicationController if ActiveStorage is included in the project?

Somewhat relevant thread around making url reference simpler within an app: Add top-level Rails.application.url for canonical reference · Issue #39566 · rails/rails · GitHub

1 Like

Perhaps related I found if you use the Rails helpers then you don’t need to both configuring ActiveStorage. For example when a model had:

def logo_url
  logo.url if logo.attached?

I got the above error in my test suite because the test suite uses the disk storage. But when I changed it to:

def logo_url
  Rails.application.routes.url_helpers.url_for logo if logo.attached?

Now it correctly gave the full URL based on the default url configuration options.