CarrierWave: Create the same, unique filename for all versioned files

后端 未结 3 1210
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-02 11:46

Before I go into detail I\'ll get right to the point: has anyone figured out a way to get Carrierwave to save files with their names as a timestamp or any arbitrary string that

3条回答
  •  Happy的楠姐
    2021-02-02 12:17

    Check also the solution from carrierwave wiki available now https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Use-a-timestamp-in-file-names

    You can include a timestamp in filenames overriding the filename as you can read in Carrierwave docs:

     class PhotoUploader < CarrierWave::Uploader::Base
         def filename
           @name ||= "#{timestamp}-#{super}" if original_filename.present? and 
           super.present?
        end
    
       def timestamp
         var = :"@#{mounted_as}_timestamp"
         model.instance_variable_get(var) or model.instance_variable_set(var, Time.now.to_i)
       end
     end
    

    Don't forget to memorize the result in an instance variable or you might get different timestamps written to the database and the file store.

提交回复
热议问题