如何在 Rails 5.2 中复制存储在 ActiveStorage 中的文件

How do I duplicate a file stored in ActiveStorage in Rails 5.2

我有一个使用 ActiveStorage 的模型:

class Package < ApplicationRecord
  has_one_attached :poster_image
end

如何创建包含初始 poster_image 文件副本的包对象的副本。大致如下:

original = Package.first
copy = original.dup
copy.poster_image.attach = original.poster_image.copy_of_file

更新您的模型:

class Package < ApplicationRecord
  has_one_attached :poster_image
end

将源包的海报图像 blob 附加到目标包:

source_package.dup.tap do |destination_package|
  destination_package.poster_image.attach(source_package.poster_image.blob)
end

如果您想要文件的完整副本,那么原始记录克隆的记录都有自己的副本附加文件,执行此操作:

在Rails 5.2中,抓取this code并将其放入config/initializers/active_storage.rb,然后使用此代码进行复制:

ActiveStorage::Downloader.new(original.poster_image).download_blob_to_tempfile do |tempfile|
  copy.poster_image.attach({
    io: tempfile, 
    filename: original.poster_image.blob.filename, 
    content_type: original.poster_image.blob.content_type 
  })
end

在 Rails 5.2 之后(只要发布包含 this commit),您就可以这样做:

original.poster_image.blob.open do |tempfile|
  copy.poster_image.attach({
    io: tempfile, 
    filename: original.poster_image.blob.filename, 
    content_type: original.poster_image.blob.content_type 
  })
end

乔治,感谢您的原始回答和您的 Rails 贡献。 :)

通过查看 Rails 的测试找到了答案,特别是 in the blob model test

所以对于这种情况

class Package < ApplicationRecord
  has_one_attached :poster_image
end

您可以复制附件

original = Package.first
copy = original.dup
copy.poster_image.attach \
  :io           => StringIO.new(original.poster_image.download),
  :filename     => original.poster_image.filename,
  :content_type => original.poster_image.content_type

同样的方法适用于 has_many_attachments

class Post < ApplicationRecord
  has_many_attached :images
end

original = Post.first
copy = original.dup

original.images.each do |image|
  copy.images.attach \
    :io           => StringIO.new(image.download),
    :filename     => image.filename,
    :content_type => image.content_type
end

在 rails 5 中效果很好。对于 Rails 6,我不得不修改为:

  image_io = source_record.image.download
  ct = source_record.image.content_type
  fn = source_record.image.filename.to_s
  ts = Time.now.to_i.to_s

  new_blob = ActiveStorage::Blob.create_and_upload!(
    io: StringIO.new(image_io),
    filename: ts + '_' + fn,
    content_type: ct,
  )

  new_record.image.attach(new_blob)

来源:

它对我有用:

copy.poster_image.attach(original.poster_image.blob)

对本杰明的回答稍作改动对我有用。

copy.poster_image.attach({
    io: StringIO.new(original.poster_image.blob.download), 
    filename: original.poster_image.blob.filename, 
    content_type: original.poster_image.blob.content_type 
  })