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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With