'Rails ActiveStorage Variants url
I'm trying to create an api to get a model's original image and other variants. Right now I'm not storing attachments on external storage, but I plan to save them on S3 in future.
Now I'm asking which is the best way to get images url?
If using url_for
the result is: /rails/active_storage/blobs/redirect/...
or /rails/active_storage/representations/redirect/...
for variants,
while processed.url
is returning /rails/active_storage/disk/...
_model.jbuilder
json.image url_for(model.image)
json.image_thumbnail url_for(model.image.variant(:thumbnail).processed)
json.image_icon model.image.variant(:icon).processed.url
Solution 1:[1]
I suggest rather than getting the stored URL to use activeStorage's proxy url and does not issue a redirect.
This allows the storage provider to change and ideally you'd cache this response with a CDN like CloudFront if you're on AWS:
json.image_thumbnail rails_storage_proxy_path(model.image.variant(:thumbnail))
More on that here: https://blog.saeloun.com/2021/06/22/rails-active-storage-proxy.html and also in the guides: https://edgeguides.rubyonrails.org/active_storage_overview.html#proxy-mode
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | JP Silvashy |