使用Paperclip删除一个图片

10

我正在使用Paperclip在我的Rails应用程序中保存图片:

用户模型:

class User < ActiveRecord::Base
  has_one :profile
end

个人资料模型:

class Profile < ActiveRecord::Base
  has_attached_file :avatar, :styles => {:medium => "300x300>", :thumb => "100x100>"}
  belongs_to :user
end

我尝试通过以下方式删除头像:

current_user.profile.avatar = nil
current_user.profile.save

但它不能工作。这可能吗?

1个回答

14
profile = current_user.profile
profile.avatar.destroy
profile.save

您无法通过此方式保存对象:current_user.profile.save


这样,文件将从文件系统中删除,但是在个人资料表中,avatar_file_name字段不会被设置为nil。我尝试手动使用以下代码将该字段设置为nil:current_user.profile.avatar_file_name = nil; current_user.profile.save; 但它没有起作用。 - Marco Antelmi
@MarcoAntelmi,您把这个答案放在哪里才能使其正常工作? - jmcastel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接