t56k
t56k

Reputation: 6981

Activestorage: get S3 key (not Rails blob key)

I'm using Activestorage. I want to retrieve the S3 key to hand off to a microservice. I don't want to download the blob or anything like that in the Rails app, I just want to provide the file path/key in an API request.

service_url is overkill because I already have access the bucket in the microservice, not to mention the fact that these are large files and I don't need to transfer them unnecessarily.

What are my options?

Upvotes: 3

Views: 3364

Answers (2)

t56k
t56k

Reputation: 6981

So while @bo-oz did link to helpful discussion it didn't really answer the question, so, to retrieve the key under which the file is stored on S3:

class User < ApplicationRecord
  has_one_attached :logo

  def logo_key_on_s3
    logo&.service_url&.split('?')&.first
  end
end

This just generates a service URL and strips out all the access tokens, expiry, etc., which is all I need since the microservice already has bucket access.

Upvotes: 1

llhhaa
llhhaa

Reputation: 307

Using service_url is not only overkill, it also runs into issues if you try to use it outside of the ActiveStorage controller, as described here.

Better is ActiveStorage#key, which for S3 will return just the S3 key to your object. It is still not what you're supposed to use for public values - ActiveStorage#signed_id gives you the railsy key. But if you want the raw S3 key (as I did for a service API), key works and doesn't complain outside of the controller.

So in your case:

def logo_key_on_s3
  logo.key
end

should work.

Upvotes: 6

Related Questions