How to update/rename a carrierwave uploaded file?

后端 未结 6 1326
我在风中等你
我在风中等你 2021-02-04 20:30

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.

<
6条回答
  •  [愿得一人]
    2021-02-04 21:08

    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!

提交回复
热议问题