Pie*_*ain 5 ruby clone ruby-on-rails amazon-s3 rails-activestorage
我正在开发一个 Ruby-on-Rails 项目,使用链接到 AWS-S3 的 ActiveStorage 进行文件上传和存储。我使用小丑gem 来克隆我的对象。
我想克隆一个带有附加文件的对象,同时也克隆这个文件(所以也在 AWS-S3 中克隆它)。
我在谷歌上看了很长时间,发现clowne_active_storage gem 来管理 ActiveStorage 附件克隆。
但我的问题是,当我尝试克隆多个对象时,克隆对第一个对象运行良好,而对其他对象不起作用。
我的用户模型:
class User < ApplicationRecord
MAX_FILE_SIZE = 30.megabytes
MAX_FILE_SIZE_HR = "30MB" #human readable
validate :validate_fields
has_one_attached :file_input
def has_attachment?
!self.file_input.attachment().nil?
end
private
def validate_fields
validate_file_size
end
def validate_file_size
if file_input.attached? && file_input.blob.byte_size > MAX_FILE_SIZE
file_input.purge
errors[:base] << ("File size should be less than " + MAX_FILE_SIZE_HR)
end
end
end
Run Code Online (Sandbox Code Playgroud)
我克隆多个对象的代码:
self.users.each { |user|
user_copy = UserCloner.call(user).to_record
user_copy.save!
}
Run Code Online (Sandbox Code Playgroud)
我的 UserCloner 类的代码(使用小丑gem):
class UserCloner < Clowne::Cloner
adapter :active_record
include_attached :file_input
# on clone finalize (_source = user & record = user_copy)
finalize do |_source, record, params|
if _source.has_attachment?
# Clone attached file
record.file_input.attach(_source.file_input.blob)
end
end
end
Run Code Online (Sandbox Code Playgroud)
所以当我克隆用户时,file_input 为第一个成功克隆,但没有为其他人成功克隆。使用调试器,我看到了一些奇怪的东西:当我检查file_input第一个克隆用户时,我的克隆用户Attachment.record等于我的克隆用户(id = nil,因为它在 user_copy.save 之前!):
<ActiveStorage::Attached::One:0x00005646cd9cc3f8 @name="file_input", @record=#<User id: nil...
Run Code Online (Sandbox Code Playgroud)
但是对于以下克隆用户,我Attachment.record等于我的源用户(_source)而不是 user_copy:
<ActiveStorage::Attached::One:0x00005646cd9608d8 @name="file_input", @record=#<User id: 1...
Run Code Online (Sandbox Code Playgroud)
我知道问题源于这里,但我不明白为什么对于第一个克隆用户,附件记录附加到克隆用户,而对于以下,附加记录附加到原始用户。
如果有人遇到同样的问题,或者有一个解决方案的开始,我会很高兴!
非常感谢您提前提供帮助,
祝您有愉快的一天,
皮埃尔·阿维南