@@ -687,6 +687,48 @@ previewable files. You can also call these methods directly.
687
687
[`representable?`] : https://api.rubyonrails.org/classes/ActiveStorage/Blob/Representable.html#method-i-representable-3F
688
688
[`representation`] : https://api.rubyonrails.org/classes/ActiveStorage/Blob/Representable.html#method-i-representation
689
689
690
+ # ## Lazy vs Immediate Loading
691
+
692
+ By default, Active Storage will process representations lazily. This code :
693
+
694
+ ` ` ` ruby
695
+ image_tag file.representation(resize_to_limit: [100, 100])
696
+ ` ` `
697
+
698
+ Will generate an `<img>` tag with the `src` pointing to the
699
+ [`ActiveStorage::Representations::RedirectController`][]. The browser will
700
+ make a request to that controller, which will return a `302` redirect to the
701
+ file on the remote service (or in [proxy mode](#proxy-mode), return the file
702
+ contents). Loading the file lazily allows features like
703
+ [single use URLs](#public-access) to work without slowing down your initial page loads.
704
+
705
+ This works fine for most cases.
706
+
707
+ If you want to generate URLs for images immediately, you can call `.processed.url` :
708
+
709
+ ` ` ` ruby
710
+ image_tag file.representation(resize_to_limit: [100, 100]).processed.url
711
+ ` ` `
712
+
713
+ The Active Storage variant tracker improves performance of this, by storing a
714
+ record in the database if the requested representation has been processed before.
715
+ Thus, the above code will only make an API call to the remote service (eg. S3)
716
+ once, and once a variant is stored, will use that. The variant tracker runs
717
+ automatically, but can be disabled through `config.active_storage.track_variants`.
718
+
719
+ If you're rendering lots of images on a page, the above example could result
720
+ in N+1 queries loading all the variant records. To avoid these N+1 queries,
721
+ use the named scopes on [`ActiveStorage::Attachment`][].
722
+
723
+ ` ` ` ruby
724
+ user.avatars.with_all_variant_records.each do |file|
725
+ image_tag file.representation(resize_to_limit: [100, 100]).processed.url
726
+ end
727
+ ` ` `
728
+
729
+ [`ActiveStorage::Representations::RedirectController`] : https://api.rubyonrails.org/classes/ActiveStorage/Representations/RedirectController.html
730
+ [`ActiveStorage::Attachment`] : https://api.rubyonrails.org/classes/ActiveStorage/Attachment.html
731
+
690
732
# ## Transforming Images
691
733
692
734
Transforming images allows you to display the image at your choice of dimensions.
0 commit comments