Skip to content

Conversation

@himanshukale36
Copy link

@himanshukale36 himanshukale36 commented Jul 16, 2025

…direct upload

Motivation / Background

This Pull Request introduces support for providing a custom key prefix when performing a direct upload using ActiveStorage. The motivation behind this change is to give developers more control over file storage paths — for example, to organize uploads by user or context (uploads/:user_id/:uuid/). Previously, ActiveStorage generated the full key automatically, which made such structuring difficult to implement cleanly.

Fixes #55340

This change supports use cases like:

  • Uploads grouped per user or project (uploads/42/...)
  • Cleaner and predictable GCS directory structures
  • Better integration with external processing pipelines that rely on path-based organization

Detail

  • Introduced logic in ActiveStorage::Blob.create_before_direct_upload! to append a secure token to a custom key prefix when key: is provided.
  • Ensured the final key format is: uploads/1//<secure_token>
  • Updated relevant documentation (README.md) to illustrate how to provide a custom prefix using data-key.
  • Added a test in test/controllers/direct_uploads_controller_test.rb to assert the correct key behavior when a prefix is supplied.
  • Ensured backwards compatibility with the original automatic key generation behavior when key is omitted.

Additional information

This change maintains backward compatibility. If no key is passed explicitly, the default behavior remains unchanged.

The token appended at the end of the provided prefix is generated via generate_unique_secure_token, consistent with the original internal format.

Checklist

Before submitting the PR make sure the following are checked:

  • This Pull Request is related to one change. Unrelated changes should be opened in separate PRs.
  • Commit message has a detailed description of what changed and why. If this PR fixes a related issue include it in the commit message. Ex: [Fix #issue-number]
  • Tests are added or updated if you fix a bug or add a feature.
  • CHANGELOG files are updated for the changed libraries if there is a behavior change or additional feature. Minor bug fixes and documentation changes should not be included.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

1 participant