When replacing an image in Active Storage, how do I run validations for the new image before purging the old image?

446 views Asked by At

I'm pretty new to Active Storage so I may be approaching this incorrectly. My application consists of a backend API utilizing Active Storage with a React frontend. When a user uploads an avatar, the frontend sends an update request with the attached image and user id. If the user already has an avatar, it purges the existing image and attaches the new image. Is there a way to run validations prior to purging the old image? Alternatively, is there a better workflow replacing files in active storage?

I'm using Rails 5.2 and Ruby 2.5.3.

User controller:

    class UsersController < ApplicationController
      def update
        user = User.find(params[:id])
        if params[:avatar] && user.avatar.attached?
          user.avatar.purge
          user.avatar.attach(user_params[:avatar])
          user.save!
        elsif params[:avatar]
          user.avatar.attach(user_params[:avatar])
          user.save!
        end
      end

      private
        def user_params
          params.permit(:id, :avatar)
        end
    end

User model:

class User < ApplicationRecord
  has_secure_password

  has_one_attached :avatar
  validate :acceptable_image

  def acceptable_image
    return unless avatar.attached?
    unless avatar.byte_size <= 1.megabyte
      error.add(:avatar, "Image exceeds 1 MB limit")
    end

    acceptable_types = ["image/jpeg", "image/png"]
    unless acceptable_types.include?(avatar.content_type)
      errors.add(:avatar, "File type must be JPEG or PNG")
    end
  end
end
0

There are 0 answers