Search code examples
ruby-on-railsactiverecordruby-on-rails-6rails-activestorage

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

Solution

  • 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