Ask A Question

Notifications

You’re not receiving notifications from this thread.

Generate ActiveStorage image variants after upload

Mitja Čebokli asked in Rails

I have a model that has a photo attached and this photo has few variants.
I would like to display many of these photos as a gallery and i am using one of the variants as a thumbnail and another one as a light box representation. Pretty straightforward.

I noticed that this variants are generated on first request, which can take quite some time for the first user as there can be many photos in a single gallery.

Is there a way to generate variants after the model has been successfully saved?
Preferably in background.

I was searching around and could't find any resources on this, but maybe i was not persistent enough :)
Anyway, I would appreciate any tips on this.

Reply

Hey Mitja, this post is a bit old now but maybe I can help the next person looking for this information :)

The way I've dealt with this exact same situation was with a job (ActiveJob or Sidekiq or whatever you choose to use). On the model that has the photo attachment, I have a callback like this:

after_commit :process_images, if: :photos_attached?

process_images simply calls a job: ProcessImagesJob.perform_later(self)

ProcessImagesJob looks something like this. I removed my app specific code, but hopefully you'll get the idea:

photos.each do |photo|
   next unless photo&.representable?

    preview_variant = photo.representation(resize_to_limit: [300, 300])
    large_variant = photo.representation(resize_to_limit: [1000, 1000])

    preview_variant.processed
    large_variant.processed
end

This generates the variant files on my storage provider, so they're ready to be used when the user views the image. Hope that helps!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.