views:

514

answers:

2

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.

+2  A: 

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))
end

record.image_file_name = new_file_name
record.save
Voyta
+3  A: 

Have you checked out paperclip interpolations?

If it is something that you can figure out in the controller (before it gets saved), you can use a combination of the controller, model, and interpolation to solve your problem.

I have this example where I want to name a file based on it's MD5 hash.

In my controller I have:

params[:upload][:md5] = Digest::MD5.file(file.path).hexdigest

I then have a config/initializers/paperclip.rb with:

Paperclip.interpolates :md5 do|attachment,style| 
  attachment.instance.md5
end

Finally, in my model I have:

validates_attachment_presence :upload
has_attached_file :upload,
  :path => ':rails_root/public/files/:md5.:extension',
  :url => '/files/:md5.:extension'
Fotios