How to update/rename a carrierwave uploaded file?

user892583 picture user892583 · Oct 18, 2012 · Viewed 7.2k times · Source

I cant figure out how to update/rename a file uploaded/managed with Carrierwave-mongoid in rails 3.2.6. I want to rename the file in the db as well as on the filesystem.

Something like this maybe...

def rename( id , new_name )
  f = UploadedFile.find(id)

  if f.update_attributes({ f.file.original_filename: new_name })  # this is WRONG, what is right???
    new_path = File.join( File.dirname( f.file.current_path ) , new_name ))
    FileUtils.mv( f.file.current_path , new_path )
  end

  return f
end

Let me add this is after it has been uploaded already.

Answer

user892583 picture user892583 · Oct 19, 2012

I was able to get the following working, although I'm sure there is a more elegant way. I'd appreciate any comments on the following

*add this to app/uploaders/file_uploader.rb

def rename(new_name)
  sf = model.file.file
  new_path = File.join( File.dirname( sf.file ) , "#{new_name}#{File.extname( sf.file )}")
  new_sf = CarrierWave::SanitizedFile.new sf.move_to(new_path)
  model.file.cache!(new_sf)
  model.save!
  return model
end

Thanks!