moiristo / deep_cloneable

This gem gives every ActiveRecord::Base object the possibility to do a deep clone that includes user specified associations.
MIT License
786 stars 88 forks source link

Fix documentation for Active Storage usage in Rails 6.1 #148

Open rossatboulder opened 1 year ago

rossatboulder commented 1 year ago

When cloning models with ActiveStorage attachments, I was encountering errors like this: Errno::ENOENT (No such file or directory @ rb_file_s_size - /tmp/ActiveStorage when using code like this:

# Rails 6
pirate.deep_clone include: :parrot do |original, kopy|
  if kopy.is_a?(Pirate) && original.avatar.attached?
    original.avatar.open do |tempfile|
      kopy.avatar.attach({
        io: File.open(tempfile.path),
        filename: original.avatar.blob.filename,
        content_type: original.avatar.blob.content_type
      })
    end
  end
end

I fixed the errors by changing the code to:

# Rails 6.1
pirate.deep_clone include: :parrot do |original, kopy|
  if kopy.is_a?(Pirate) && original.avatar.attached?
      kopy.avatar.attach({
        io: StringIO.new(original.avatar.download),
        filename: original.avatar.filename,
        content_type: original.avatar.content_type
      })
  end
end