Custom key for ActiveStorage blobs

Hi there,

Does anyone know if there’s a simple solution to customize the ActiveStorage Blob’s key format?

My use case: for images, I’d like to be able to generate public link such as https://example.com/folder/random-string/filename.png , where ‘folder/random-string/filename.png’ is the blob’s key. That way, the asset could be requested directly from the S3 backend (or the CDN) without going through the Rails app (I am using an S3 backend with public buckets).

Thanks! Fabrice.

1 Like

As far as I know, there’s not way to change that key. However, if your files are public, there’s another setup you can use to avoid the proxy controller, but still get caching (I’m using Cloudflare as an example):

  1. Go to S3 and create a bucket named assets.example.com.
  2. Set that bucket as your active-storage bucket in storage.yml, set it to public: true
  3. Go into Cloudflare and create a CNAME for that bucket: assets.example.comassets.example.com.s3.us-east-1.amazonaws.com
  4. Add cloudflare page rules to force caching in the subdomain;
  5. Finally, instead of passing blob to the image_tag, do this:
image_tag blob.url(virtual_host: true)

The end result will be something like this:

<img src="https://assets.example.com/ozf663sus62msm00fwcycqadnnqp"/>

And due to the rule, Cloudflare will cache it.

I believe this Stack Overflow post describes what you’re asking for.

Thanks Breno and William. Although proposed solutions work, they do not offer the possibility to have a custom key (which would be build with the filename (in the initial example, ‘folder/random-string/filename.png’ would be the key). Setting the bucket public does not allow such mechanism. I finally ended up doing something which is (very) far from being perfect, but which works in my case: updating keys once the ActiveStorage process is done (that’s not perfect and some S3 providers may charge for that since the file needs to be moved but with the provider I use, that’s free).