Copying / Cloning an ActiveStorage attribute

I want to clone an attached image to another model. Either as:

  1. a reference, such that the attachment won't be deleted until all the referring objects are deleted

  2. by cloning the attachment and having it as a distinct replica...

How does rails handle ActiveStorage attachments? Do they get deleted automatically when the model goes or does it need to be done manually? Is there a reference counting mechanism?


Solution 1:

This worked for me in Rails 6.1.3

model.new_file.attach(io: StringIO.new(original_file.download),
                      filename: original_file.filename,
                      content_type: original_file.content_type)