ruby-on-railsrails-activestorage

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


I have a model that is using ActiveStorage:

class Package < ApplicationRecord
  has_one_attached :poster_image
end

How do I create a copy of a Package object that contains a duplicate of the initial poster_image file. Something along the lines of:

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

Solution

  • Update your model:

    class Package < ApplicationRecord
      has_one_attached :poster_image
    end
    

    Attach the source package’s poster image blob to the destination package:

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