gpt4 book ai didi

ruby-on-rails - 使用载波共享对象中的图像

转载 作者:数据小太阳 更新时间:2023-10-29 08:01:22 26 4
gpt4 key购买 nike

我有一个原始对象 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

到目前为止,新对象一切正常,共享原始图像。这两个对象具有相同的共享图像和相同的路径。

问题是如果我删除原始对象,克隆对象找不到图像,因为我在原始帖子中删除了。

在我的 destroy 操作对象中,如何使用回调 before_destroy 检查图像是否被一个或多个对象使用

如果图像,使用2个或更多对象,

不删除图像。

否则,如果图像被单个对象使用,

删除图像。

这可能吗?

我需要一种方法来验证这个问题。

最佳答案

覆盖 CW 在您的模型中注入(inject)的 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(path) 分配给已发布的列而不是上传者。

关于ruby-on-rails - 使用载波共享对象中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9203839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com