Search code examples
ruby-on-railsherokuamazon-s3rails-activestoragerails-api

Getting heroku-app url for images instead of s3.amazonaws in Active storage Rails API


I am having difficulty in understanding the image url of active storage in rails. I am using amazon s3 bucket for uploading images in production with proper configuration in storage.yml file.

When I run url_for(User.user_image), it generates this link:

http://my-heroku-app/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBdVFCIiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--1207b8339755bdc5391cb96548181a27dd9565fc/testing_image.jpg

and when I run User.user_image.service_url, the generated link is

https://my-app.s3.amazonaws.com/ySMyXZUWDnQGexvvNwKjZKpb......

Are my images being stored at 2 places? one is Heroku-PostgreSQL and second is aws-s3 or is it just aws-s3 where my images are being stored and active storage is somehow binding it the s3 link.

Actually, I want http://s3.amazonaws.com in url_for to return it in the API response.

Application Behavior: I have Rails API application in which images/videos first comes to the rails app from the front-end and from there they are pushed to the s3 bucket.


Solution

  • The way you would want to generate the url is actually

    rails_blob_url(User.find({id of user}).user_image)
    

    As far as how this works, activestorage just holds a pointer to where the file is located and will redirect to the S3 bucket as necessary. It's actually impossible on Heroku to store files locally the way their service is constructed, some sort of external storage container is required.

    Rails documentation on the linking portion: https://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files