Search code examples
ruby-on-railsactiverecord

Rails: Active Storage how to change main image size


In the guide it is clearly explained how to create variants on upload with

class User < ApplicationRecord
  has_one_attached :avatar do |attachable|
    attachable.variant :thumb, resize_to_limit: [100, 100]
  end
end

but I can't find how to change the size and store that resized image on User.avatar, the Active Storage managed attachment.

I made several attempts like this:

has_one_attached :avatar, dependent: :destroy

before_save :preprocess_image

def preprocess_image
    return unless avatar.attached?
    logger.info("imagen size"+avatar.blob.byte_size.to_s)
    avatar.resize(400,400)
end

but I got errors like this:

undefined method `resize' for #<ActiveStorage::Attached::One:0x000055a8c8518008>

What can I do?


Solution

  • I was able to solve this problem, by intercepting the image and using directly the image processing library at the controller.create time, and updating the parameter before sending it to active storage.

      path = user_params[:image].tempfile.path
      vips_image = ImageProcessing::Vips.source(path).resize_to_limit(200, 
        200).saver(strip: true, quality: 100)
        .convert("jpg").call
      user_params[:image].tempfile = vips_image
    

    So, active storage saves the modified image, no need to generate variants for this case.