Rails how to copy all active storage attachments to new object?

Viewed 1304

I have a function to clone records in a rails application. In addition to the form data I would like to copy/attach any active storage file uploads that are attached to the source object to the new object. Any ideas on how to do this? Here is my action:

def copy
  @source = Compitem.find(params[:id])
  @compitem = @source.dup
  render 'new'
end

class Compitem < ApplicationRecord
 belongs_to :user
 has_many_attached :uploads, dependent: :destroy
end
2 Answers

I ended up getting this working by using the https://github.com/moiristo/deep_cloneable gem. Final action:

  def copy
   @source = Compitem.find(params[:id])
   @compitem = @source.deep_clone(include: :uploads_blobs)
   @compitem.save
   render 'new'
  end

Just did this in one of my applications - it was a has_one rather than has_many but I think something like this should work for you, without adding any additional dependencies, in Rails 6+:

@compitem  = @source.dup
@source.uploads.each do |original_file|
  @compitem.uploads.attach(io: StringIO.new(original_file.download),
                           filename: original_file.filename,
                           content_type: original_file.content_type)
end

@compitem.save
Related