Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting ActiveStorage host

Right now I have a setup that allows users to point their apps directly to my Rails app using a CNAME (aka, point www.example.com to my app hosted at www.example2.com).

All that works great! But, I want to serve images up using my app www.example2.com as the host (for CDN reasons).

It seems like ActiveStorage is defaulting (and forcing...) the host to be the current host and not allowing me to change it.

I have:

config.action_controller.asset_host = 'https://www.example2.com'
    Rails.application.routes.default_url_options[:host] = 'https://example2.com'

and it works great for static assets! But, ActiveStorage image_tag's are still using whatever domain the site is being viewed on, in this case www.example2.com.

Thoughts on how to make it ALWAYS serve using the asset_host?

like image 286
Mike Fogg Avatar asked Oct 23 '25 10:10

Mike Fogg


1 Answers

Use ActiveStorage::Current.host which makes use of CurrentAttributes, a type of attributes that are set/reset on every request and can be used everywhere in your Rails app:

class ApplicationController
  before_action do
    ActiveStorage::Current.host = 'https://example2.com'
  end
 end

If you want to use it outside of a controller, use ActiveStorage::Current.set to provide a host:

ActiveStorage::Current.set(host: "https://www.example2.com") do
  item.file_ttachments.first.service_url
end

Rails reference docs: https://edgeapi.rubyonrails.org/classes/ActiveStorage/SetCurrent.html

like image 193
Pere Joan Martorell Avatar answered Oct 26 '25 04:10

Pere Joan Martorell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!