How can I rename all the existing carrierwave uploaded files?

534 views
Skip to first unread message

hau

unread,
Jul 4, 2013, 2:01:38 AM7/4/13
to carri...@googlegroups.com
     

I have been using Carrierwave for file uploads for some time. I did not try to rename the files as they got uploaded. Now I want to give each file a random name and a file extension that's consistent with the content type. I read the wiki and other sites, and it was recommended that in the uploader, I could:

def filename
  "#{secure_token}.#{file.extension}" if original_filename.present?
end

private
def secure_token
  #implement the secure token
end

It worked fine on files uploaded after these additions to the uploader. But I got many files that were uploaded before this change. I was wondering if someone could tell me how to migrate the old files.

I tried adding a method to the uploader:

def rename_file!
  model.update_attribute mounted_as, "#{secure_token}.#{file.extension}"
  recreate_versions!
end

then in the rails console, I tried calling this on an model with attachment. However, I found that the mounted_as column of the model never got updated, though on the file system, various versions of the file were created with the new name. When I inspected the mounted_as field of the model, it did not get updated. The log actually said the column was updated with the old value.

How can I get the mounted_as column on the model updated?

In addition, it seemed like the old files with the old names were still on the file system. Is there a way to remove them? I tried adding a line:

file.move_to File.join("#{File.dirname file.path}, "#{secure_token}.#{file.extension}")

in the rename_file! method. It renamed the files, but did not update the mounted_as column on the model. So accessing its URL resulted in a 404.

Reply all
Reply to author
Forward
0 new messages