我有一个原始对象 post.rb ,包含下一个字段或属性。
class Post
include Mongoid::Document
mount_uploader :posted, PostedUploader, mount_on: :posted_filename
field :posted
field :remote_posted_url
attr_accessible :posted, :remote_posted_url
end
然后我想从第一个原始对象创建一个副本并共享新对象的图像。然后我这样做:
attribs = @post.attributes.select {|a| %w(posted remote_posted_url).include? a }
new_post = Post.new attribs
new_post.save
到目前为止,一切都运行良好的新对象,分享原始图像。这两个对象具有相同路径的共享图像。
问题是如果删除原始对象,克隆对象找不到图像,因为我在原始帖子中删除了。
如何在我的销毁操作对象中使用回调 before_destroy ,检查图像是否由一个或多个对象使用。
如果图像使用2个或更多对象,
可能吗?
我需要一种方法来验证这个问题。
答案 0 :(得分:3)
覆盖模型中CW注入的remove_posted
回调:
class Post
include Mongoid::Document
mount_uploader :posted, PostedUploader, mount_on: :posted_filename
field :posted
field :remote_posted_url
attr_accessible :posted, :remote_posted_url
# override as to not delete if there's another model storing the same image
def remove_posted!
super unless Post.where(posted_filename: posted_filename).count > 1
end
end
PS:Post.new(attribs).save
应该复制文件,而不是使用相同的文件,也许您应该将File.open(路径)分配给上传者发布的已发布列。