Search code examples
ruby-on-railsamazon-s3ruby-on-rails-5rails-activestorage

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?


Solution

  • 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.