Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

carrierwave: point to existing image

In my rails app, I'm using Carrierwave to upload images on Amazon S3. I'd like to point to existing Amazon S3 images without having to re-upload the image. For example, if I have an existing Amazon S3 image at http://test.s3.amazonaws.com/image/path/0001/image.jpg, can I update an image's path to point to this image? I don't want to use the remote upload option because I really just want to use the same exact image that's already there (but save it in my record's "path" attribute).

In the console, I've tried:

image.update_attributes(:path=> "http://test.s3.amazonaws.com/image/path/0001/image.jpg")

but this fails to override the image's path.

like image 544
scientiffic Avatar asked Jul 14 '13 01:07

scientiffic


2 Answers

Chiming in, better late than never! Caveat: This is for rails 4, and I am testing on rails 4.1 only at the moment.

This is harder than it should be, methinks! The reason this was absolutely crucial to me was that I am attaching 100MB+ MP3 files, which I cannot receive on my host, due to CloudFlare SSL limitations (and common sense). Fortunately, AWS supports preauthorized uploads, and I got carrierwave to do the right thing for me:

Step 1: get carrierwave to tell me where it would store a file if it could:

 m.raw_write_attribute('file','file.mp3');
 url = m.file.url
 signed = aws_presigned_url(url)

raw_write_attribute does not save anything, it just bypasses carrierwave when setting the value. This makes the object act as if it read 'file.mp3' out of the database. Then you can ask Carrierwave "where the file lives". I then upload the file directly from the client to S3. When that's done, I make another API call to Rails, which performs the following code:

 m.raw_write_attribute('file','file.mp3');
 m.update_attribute('file','file.mp3');

These two paired get around Carrierwave. The first makes carrierwave think that the 'file' column is set to 'file.mp3', the second explicitly tells rails to persist 'file.mp3' to the DB. Because of the raw_write_attribute call, Carrierwave allows the second through un-changed.

like image 168
Daniel Avatar answered Sep 19 '22 17:09

Daniel


In my case update_column and update_columns worked great:

model.update_columns file_1: 'filename.txt'

Update column is with comma:

model.update_column :file_1, 'filename.txt'

This will not run any callback and set column to filename.txt.

When I do model.file_1.url I get the right S3 URL.

like image 38
sites Avatar answered Sep 19 '22 17:09

sites