Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 492
spacerobot Avatar asked Feb 01 '26 10:02

spacerobot


1 Answers

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
like image 125
Buck3000 Avatar answered Feb 04 '26 01:02

Buck3000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!