Use url_for to serve files rails API

I am building an Rails API that servers json to the client. I need to include urls for images that is stored in AWS via Active Storage. The solution I have right now is include:

          def image_url
            image.attached? ? url_for(self.image) : nil
            # image.url
          end

in the model and include the url in the controller:

      def set_product_json(product)
        product.as_json.merge(image_url: product.image_url)
      end

However, the problem I am having is my client end up firing a GET request like this:

curl 'https://XXXX/rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsiZGF0YSI6MSwicHVyIjoiYmxvYl9pZCJ9fQ==--215989b455658c6cab7d0e758416a770e371fef7/1000828342.jpg'

which is as expected according to the doc. But somehow I end up download the image twice, once with this GET request, once with the redirect AWS S3 endpoint, as the screenshot shows below. This is inefficient. Is this the expected behavior? I read from the doc that url_for is the way to serve files. Is there a better way to generate the url? A screenshot of the network tab

The first call is a “preflight” kind of link, giving you a http 302 with the final url - so it’s not a double download - it’s a part of the process of getting the final link to the resource

1 Like