Search code examples
ruby-on-railsrails-activestorage

Missing host problem when using Active Storage in Rails


I don't want that our servers are touched more than needed (we are using CDN for that purpose) I want to use direct links to resources (without active storage redirects)

Direct link can be retreived via

object.active_storage_file.service_url

But this results with an error:

Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

In env/development.rb I already added :

Rails.application.routes.default_url_options[:host] = "localhost:3000"

However this doesn't solve the problem. Any idea why and how to do this?


Solution

  • In your controller you can write:

    before_action do
       ActiveStorage::Current.host = request.base_url
    end
    

    That would let you give the service url with the host by using say:

    active_storage_file.blob.service_url if active_storage_file.attached?