Duplicate A Record With An Image

What is the suggested way to duplicate a record with a Shrine image?

On development I serve images from the file system, but on production and staging I serve images from S3.

I was doing the following, but it appears the original images are broken on S3 afterwards.

def duplicate
  duplication = self.dup
  duplication.name = "Copy of #{self.name}"
  # bunch of other logic
  duplication.image_remote_url = self.image_url(host: ENV['STORAGE_URL'])
  duplication.save
  duplication 
end	

I thought that pointing the duplicate image_remote_url to the source image URL should copy over the image?

Do I need to do something like the following to remove all existing image data?

duplication.image = nil
duplication.image_remote_url = self.image_url(host: ENV['STORAGE_URL'])
duplication.save

Any help would be greatly appreciated!

PS I did read https://shrinerb.com/docs/upgrading-to-3#copy but wasn’t sure how to get this working.

The current advice in upgrading guide on replacing the copy plugin is incorrect, as it causes the original image to get deleted when the duplicate record is saved.

It’s since been corrected, and should be live once Shrine 3.3.0 is released. The following should work:

duplication = self.dup
duplication.image_attacher.set image_attacher.upload(image)
duplication.save

Attacher#upload will copy the original image to a different location, and then Attacher#set will assign the new uploaded file, without marking the original file as “replaced”.

2 Likes

Thank you @janko! This was the exact problem I experienced, it broke all images and files in the original model, thanks for pointing me in the right direction. :pray: