我的用户模型有头像附件
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
上传图片之前avatar.url返回默认url,当我上传图片并保存然后删除它时,avatar.url仍然指向已删除的图片url而不是default_url
我用下面的代码删除头像:
user.avatar = nil
user.save
检查后也尝试了这些方法 question 1和 question2 关于同样的问题
user.avatar.destroy
user.save
#also tried this
user.update(avatar_file_name: nil, avatar_content_type: nil, avatar_file_size: nil)
我正在使用 rails 5.1.6,回形针 (~> 5.2.0)
最佳答案
您需要使用purge
,而不是destroy
。来自官方文档,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
按照您所做的方式删除 Assets 不会删除实例与 Assets 之间的附件:
user.avatar.destroy
user.avatar.attached? => true
user.avatar.purge
user.avatar.attached? => false
关于ruby-on-rails - Rails Paperclip,使用 default_url 选项删除附件不会更改附件 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55047607/