views:

324

answers:

2

I'm using paperclip for attachments in my application. I'm writing an import script for a bunch of old data, but I don't know how to create paperclip objects from files on disk. My first guess is to create mock CGI multipart objects, but that seems like a bit of a crude solution, and my initial attempt failed, I think because I didn't get the to_tempfile method right.

Is there a Right Way to do this? It seems like something that should be fairly easy.

+2  A: 

I know that I've done the same thing, and I believe that I just created a File object from the path to each file, and assigned it to the image attribute. Paperclip will run on that file:

thing.image = File.new("/path/to/file.png")
thing.save
Ben
Note to self, try the simplest thing that could possibly work next time.
Zak
I recall being as surprised as you.
Ben
Yeah -- this absolutely rocks
John Paul Ashenfelter
+2  A: 

This works great for local files but it doesn't work as well for remote files. I have an app that uses paperclip for uploading images. Those images are getting stored on amazon s3. Anyway, I had some old data that I needed to import so I tried the following:

thing.image = open('http://www.someurl.com/path/to/image.jpg')
thing.save

If the file is small (say, less than 10K) then openuri returns a stringio object and my file would get stored on s3 as stringio.txt

If the file is larger than around 10K, then openuri returns a TempFile object. But the filename on s3 ends up being unique, but not really relating to the original filename of image.jpg

I was able to fix the problem by doing the following:

remote_photo = open('http://www.someurl.com/path/to/image.jpg')
def remote_photo.original_filename;base_uri.path.split('/').last; end   
thing.image = remote_photo
thing.save
Francois