3
votes

My user model has avatar attachment

class User
  has_attached_file :avatar, styles: { medium: '300x300#', thumb: '150x150#' }, default_url: :default_url_by_gender

  def default_url_by_gender
    if female?
      'female.svg'
    else
      'male.svg'
    end
  end
end

Before uploading an image the avatar.url return default url, when I upload an image and save then delete it, the avatar.url still direct to the deleted image url not the default_url

I delete the avatar with following code:

user.avatar = nil
user.save

and also tried these methods after checking question 1 and question2 about same issue

user.avatar.destroy
user.save

#also tried this
user.update(avatar_file_name: nil, avatar_content_type: nil, avatar_file_size: nil)

I am using rails 5.1.6, paperclip (~> 5.2.0)

1

1 Answers

1
votes

You need to use purge, not destroy. From the official docs, https://edgeguides.rubyonrails.org/active_storage_overview.html#removing-files

To remove an attachment from a model, call purge on the attachment. Removal can be done in the background if your application is setup to use Active Job. Purging deletes the blob and the file from the storage service.

# Synchronously destroy the avatar and actual resource files.
user.avatar.purge

# Destroy the associated models and actual resource files async, via Active Job.
user.avatar.purge_later

Deleting the asset in the way you've done does not remove the attachment between the instance and the asset:

user.avatar.destroy
user.avatar.attached? => true

user.avatar.purge
user.avatar.attached? => false