Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

amazon s3 and carrierwave random image name in bucket does not match in database

I'm using carrier wave, rails and amazon s3. Every time I save an image, the image shows up in s3 and I can see it in the management console with the name like this:

https://s3.amazonaws.com/bucket-name/ uploads/images/10/888fdcfdd6f0eeea_1351389576.png

But in the model, the name is this:

https://bucket-name.s3.amazonaws.com/ uploads/images/10/b3ca26c2baa3b857_1351389576.png

First off, why is the random name different? I am generating it in the uploader like so:

def filename
  if original_filename
    "#{SecureRandom::hex(8)}_#{Time.now.to_i}#{File.extname(original_filename).downcase}"
  end
end

I know it is not generating a random string every call because the wrong url in the model is consistent and saved. Somewhere in the process a new one must be getting generated to save in the model after the image name has been saved and sent to amazon s3. Strange.

Also, can I have the url match the one in terms of s3/bucket instead of bucket.s3 without using a regex? Is there an option in carrierwave or something for that?

like image 821
AJcodez Avatar asked Oct 28 '12 02:10

AJcodez


2 Answers

CarrierWave by default doesn't store the URL. Instead, it generates it every time you need it.

So, every time filename is called it will return a different value, because of Time.now.to_i.

Use created_at column instead, or add a new column for storing the random id or the full filename.

like image 63
glebm Avatar answered Sep 27 '22 16:09

glebm


I solved it by saving the filename if it was still the original filename. In the uploader, put:

def filename
  if original_filename && original_filename == @filename
    @filename = "#{any_string}#{File.extname(original_filename).downcase}"
  else
    @filename
  end
end

The issue of the sumbdomain versus the path is not actually an issue. It works with the subdomain. I.e. https://s3.amazonaws.com/bucket-name/ and https://bucket-name.s3.amazonaws.com/ both work fine.

like image 24
AJcodez Avatar answered Sep 27 '22 17:09

AJcodez