Active Storage set blob key on direct upload (changelog)

Referencing this PR: Allow providing a custom key per blob · rails/rails@4dba136 · GitHub We can now specify a blob key when using the traditional attach method. However, I cannot figure out how to specify the key when using direct uploads. The direct upload method was also updated in this PR, so I’m hoping I’m missing something.

As far as I can tell, if I want to send in a custom key such as using direct uploads I…can’t? I’d have to hook in here: rails/activestorage.js at b5dac96b59a582c7968b0c33d6ff39d1cfc336dc · rails/rails · GitHub var blob = new BlobRecord(_this.file, checksum, _this.url); Even if I send in a this.key to my direct uploads controller, I don’t want to change the call to BlobRecord and I don’t want to patch activestorage.js b/c that will certainly cause trouble in the future.

I can override key in blob.rb, but I want to prefix based on, so I need to send in the user details somehow.

TLDR: Can I send a key variable with this new PR via direct uploads? I know this was previously not how ASt was designed, but the above PR makes me hopeful there may be a way.

1 Like

Note: On Rails 6.0
I’ve sorted out that to enable changing the key on direct uploads you can’t just override key on blob.rb because the key is being set before def key is called. By the time you hit the def key method self[:key] has already been set by generate_unique_secure_token which IIRC is called from activerecord. Anyway, since I’m only using direct uploads I patched create_before_direct_upload! to force the key in the format I want.

    def create_before_direct_upload!(filename:, byte_size:, checksum:, content_type: nil, metadata: nil)
      key = SecureRandom.base36(28) + "/" + filename
      create! key: key, filename: filename, byte_size: byte_size, checksum: checksum, content_type: content_type, metadata: metadata

Would love to hear any other ideas.