Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the proper way to copy a carrierwave file from one record to another?

Tags:

I need to copy a file from one carrier wave object to another. They are different tables and different types of uploaders.

I started with:

user.avatar = image.content 

(where user and image are model instances, avatar and content are the carrierwave mounted uploaders) which worked sometimes. It seems to work all the time locally, with a file storage, but intermittent when using fog and s3.

In a mailing list post I found this code:

user.avatar = image.content.file 

that again worked sometimes.

My working solution so far is:

require "open-uri"  begin   user.avatar = open(image.url) rescue Errno::ENOENT => e   begin     user.avatar = open(image.path)   rescue Errno::ENOENT => e     # Ok, whatever.   end end 

which is not only ugly, but fails to pass the extension validation because the opening of a remote file doesn't maintain the extension (jpg, png, etc.).

like image 926
pupeno Avatar asked Mar 29 '12 07:03

pupeno


2 Answers

Perhaps one way you can do it is to set a remote image URL as per the Carrierwave gem documentation?

user.remote_avatar_url = image.url 
like image 197
Dia Kharrat Avatar answered Sep 20 '22 13:09

Dia Kharrat


From solutions discussed here I created simple CopyCarrierwaveFile gem to do this

usage is something like this:

original_resource = User.last new_resource      = User.new  CopyCarrierwaveFile::CopyFileService.new(original_resource, new_resource, :avatar).set_file      new_resource.save nev_resource.avatar.url # https://...image.jpg 
like image 31
equivalent8 Avatar answered Sep 19 '22 13:09

equivalent8