I know how to change a filename during the upload process using
attachment_fu, however I need to change it after the create based on
additional information I don’t have during the initial upload.
Performing an attribute update on the resulting model object always
seems to ignore the “filename” attribute, but will happily update an
other attribute of the record. What gives? Is it because the record’s
filename is tied to a physical file?
Code:
params[:media_file] is the “:uploaded_data” submitted by a form to the
controller.
@media_file = MediaFile.new(params[:media_file])
if @media_file.save
@media_file.update_attributes({:desc => “blah”, :filename =>
“new_fname.ext”})
end
logger shows the “desc” attribute being updated but never the filename
attribute.
What gives and how can I make this happen?
Use Paperclip. It much more faster and powerful gem for attachments.
And take a look at Paperclip Processors
Paperclip could use custom processors to do non-standard stuff with
attachments. By default it’s just resizing images with given
parameters.
You specify your processor name like:
has_attached_file :file,
:styles => {:original => {:processors => [:file_renamer]}}
and you need to have a class in
lib/paperclip_processors/file_renamer.rb like
module Paperclip
class FileRenamer < Paperclip::Processor
…
end
end
there’s some examples in documentation. The thing is you get an
uploaded @file in your processor, and in the end you need to return
your renamed @new_file back. You could do anything with it inside and
then use another processor in chain.
Like in your case, you can create some tmp_dir, copy the @file.path to
your tmp_dir/new_file_name.ext, and return @new_file =
File.open(tmp_dir/new_file_name.ext). Then you just delete tmp_dir
with after_create filter or with cron job.