deep_cloneable icon indicating copy to clipboard operation
deep_cloneable copied to clipboard

Fix documentation for Active Storage usage in Rails 6.1

Open rossatboulder opened this issue 2 years ago • 0 comments

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

rossatboulder avatar Aug 05 '23 19:08 rossatboulder