Skip to content

Commit c204eec

Browse files
authored
Merge pull request rails#42495 from ghiculescu/patch-1
Active Storage: docs on lazy vs immediate loading
2 parents 1bd092c + 9f3c686 commit c204eec

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

guides/source/active_storage_overview.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,48 @@ previewable files. You can also call these methods directly.
709709
[`representable?`]: https://api.rubyonrails.org/classes/ActiveStorage/Blob/Representable.html#method-i-representable-3F
710710
[`representation`]: https://api.rubyonrails.org/classes/ActiveStorage/Blob/Representable.html#method-i-representation
711711

712+
### Lazy vs Immediate Loading
713+
714+
By default, Active Storage will process representations lazily. This code:
715+
716+
```ruby
717+
image_tag file.representation(resize_to_limit: [100, 100])
718+
```
719+
720+
Will generate an `<img>` tag with the `src` pointing to the
721+
[`ActiveStorage::Representations::RedirectController`][]. The browser will
722+
make a request to that controller, which will return a `302` redirect to the
723+
file on the remote service (or in [proxy mode](#proxy-mode), return the file
724+
contents). Loading the file lazily allows features like
725+
[single use URLs](#public-access) to work without slowing down your initial page loads.
726+
727+
This works fine for most cases.
728+
729+
If you want to generate URLs for images immediately, you can call `.processed.url`:
730+
731+
```ruby
732+
image_tag file.representation(resize_to_limit: [100, 100]).processed.url
733+
```
734+
735+
The Active Storage variant tracker improves performance of this, by storing a
736+
record in the database if the requested representation has been processed before.
737+
Thus, the above code will only make an API call to the remote service (eg. S3)
738+
once, and once a variant is stored, will use that. The variant tracker runs
739+
automatically, but can be disabled through `config.active_storage.track_variants`.
740+
741+
If you're rendering lots of images on a page, the above example could result
742+
in N+1 queries loading all the variant records. To avoid these N+1 queries,
743+
use the named scopes on [`ActiveStorage::Attachment`][].
744+
745+
```ruby
746+
user.avatars.with_all_variant_records.each do |file|
747+
image_tag file.representation(resize_to_limit: [100, 100]).processed.url
748+
end
749+
```
750+
751+
[`ActiveStorage::Representations::RedirectController`]: https://api.rubyonrails.org/classes/ActiveStorage/Representations/RedirectController.html
752+
[`ActiveStorage::Attachment`]: https://api.rubyonrails.org/classes/ActiveStorage/Attachment.html
753+
712754
### Transforming Images
713755

714756
Transforming images allows you to display the image at your choice of dimensions.

0 commit comments

Comments
 (0)