Search code examples
ruby-on-railsrails-activestoragesrcset

How to use image_tag with srcset and active storage variant?


I would like to use image_tag srcset attributes with active storage variants

    <%= image_tag(@assoc.photo,
    srcset:[
      [@assoc.photo.variant(resize: "600x600"), "1024w"],
      [@assoc.photo.variant(resize: "800x800"), "1980w"]
      ],
      sizes: "100vw") %>

The first line return: no implicit conversion of Symbol into Integer.

What's wrong ?


Solution

  • I did a method for resize the photos :

      def photos_variants(photo, width, height)
        variation = ActiveStorage::Variation.new(Uploads.resize_to_fill(width: width, height: height, blob: photo.blob))
        ActiveStorage::Variant.new(photo.blob, variation)
      end
    

    and I call this method in my srcset tag :

    <%= image_tag(@assoc.photo,
    srcset:[
      [url_for(@assoc.photos_variants(@assoc.photo, 400, 300)), "512w"],
      [url_for(@assoc.photos_variants(@assoc.photo, 600, 450)), "768w"],
      [url_for(@assoc.photos_variants(@assoc.photo, 800, 600)), "1024w"],
      [url_for(@assoc.photos_variants(@assoc.photo, 1200, 900)), "1980w"]
      ],
      sizes: "100vw") %>