'How to automatically delete the old file attachment when a new active-storage attachment is saved to the model

How do i delete the previously saved avatar image when the user updates the avatar.

For instance, I have tried the following in my user model

class User < ApplicationRecord

  before_validation :save_old_avatar

  def save_old_avatar
    @old_avatar = avatar.attachment
  end

  after_save do
    if avatar.attached? && avatar.new_record?
      @old_avatar&.purge
    end
  end

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable, authentication_keys: [:login_id]

  has_one_attached :avatar
end


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source