fivetwentysix fivetwentysix - 7 months ago 27
Ruby Question

Paperclip renaming files after they're saved

How do I rename a file after is has been uploaded and saved?
My problem is that I need to parse information about the files automatically in order to come up with the file name the file should be saved as with my application, but I can't access the information required to generate the file name till the record for the model has been saved.


If, for example, your model has attribute image:

has_attached_file :image, :styles => { ...... }

By default papepclip files are stored in /system/:attachment/:id/:style/:filename.

So, You can accomplish it by renaming every style and then changing image_file_name column in database.

(record.image.styles.keys+[:original]).each do |style|
    path = record.image.path(style)
    FileUtils.move(path, File.join(File.dirname(path), new_file_name))

record.image_file_name = new_file_name