Skip to content

Commit 6534a5d

Browse files
[ci skip] Update ActiveStorage Docs (rails#51157)
* Update ActiveStorage Docs Included documentation around usage of the `key` parameter in `.attach` method to specify folders within S3 Bucket for organizing files and storing them with intuitive names. * Update active_storage_overview.md lint correction - removed trailing whitespace Co-authored-by: Rafael Mendonça França <[email protected]>
1 parent 9f1dec2 commit 6534a5d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

guides/source/active_storage_overview.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,41 @@ You can bypass the content type inference from the data by passing in
588588
If you don’t provide a content type and Active Storage can’t determine the
589589
file’s content type automatically, it defaults to application/octet-stream.
590590

591+
There is an additional parameter `key` that can be used to specify folders/sub-folders
592+
in your S3 Bucket. AWS S3 otherwise uses a random key to name your files. This
593+
approach is helpful if you want to organize your S3 Bucket files better.
594+
595+
```ruby
596+
@message.images.attach(
597+
io: File.open('/path/to/file'),
598+
filename: 'file.pdf',
599+
content_type: 'application/pdf',
600+
key: "#{Rails.env}/blog_content/intuitive_filename.pdf",
601+
identify: false
602+
)
603+
```
604+
605+
This way the file will get saved in the folder `[S3_BUCKET]/development/blog_content/`
606+
when you test this from your development environment. Note that if you use the key
607+
parameter, you have to ensure the key to be unique for the upload to go through. It is
608+
recommended to append the filename with a unique random key, something like:
609+
610+
```ruby
611+
def s3_file_key
612+
"#{Rails.env}/blog_content/intuitive_filename-#{SecureRandom.uuid}.pdf"
613+
end
614+
```
615+
616+
```ruby
617+
@message.images.attach(
618+
io: File.open('/path/to/file'),
619+
filename: 'file.pdf',
620+
content_type: 'application/pdf',
621+
key: s3_file_key,
622+
identify: false
623+
)
624+
```
625+
591626
### Replacing vs Adding Attachments
592627

593628
By default in Rails, attaching files to a `has_many_attached` association will replace

0 commit comments

Comments
 (0)