Search code examples
ruby-on-railspaperclippaperclip-validation

Retroactively change paperclip size validation -> previous images now invalid


Let's say I have a paperclip attachment on my model that has a size validation of 10GB and a bunch of users upload images up to that maximum size.

If I then change the size validation to something smaller, say 5GB, any images previously uploaded that are greater than the new validation are now invalid. Thus, even trying to touch the model fails because this validation fails. Calling reprocess! on the images does not help since that just reprocesses the styles but doesn't resize the original image.

What can be done here to validate old images that no longer pass a newer, smaller size validation?


Solution

  • Ended up just writing a script using imagemagick directly to resize the existing image (50% at a time) and then resave it. Assuming a model name of Model and a paperclip attachment of picture:

    puts "Finding and resizing images from models..."
    invalid_models = Model.where("picture_file_size > 10_000_000")
    puts "Found #{invalid_models.count} models with oversized images"
    
    invalid_models.each do |m|
      puts "Model #{m.id} has image with size #{m.picture.size}"
      while(!m.valid?) do
        puts "\tShrinking by 50%..."
        tmp_filename = "/tmp/#{m.picture_file_name}"
        %x(convert #{m.picture.url} -resize 50% #{tmp_filename})
        m.picture = open(tmp_filename)
        m.save(validate: false) # skip validations in case it's still too large
        puts "\tNew size=#{m.picture.size}, valid?=#{m.valid?}"
      end
    end
    puts "Done!"