Carrierwave: rename filename / replace file

104 Views Asked by At

I already tried multiple solutions from SO, but none of them helped me.

I have uploaded file, that stored in my folder locally. I need to simply rename it's filename (I didn't find any simple way to do this) or replace file with new filename according to whole valid process for Carrierwave (with renaming filename at SanitizedFile, Attachment model, Storage::File, etc entities).

So currently I have an Attachment model with: mount_uploader :content, ContentUploader

And trying to use such code for renaming filename at the same model:

  def filename=(new_filename)
    new_filepath = File.join(File.dirname(content.file.path), new_filename)
    content.file.move_to(new_filepath)

    write_attribute :content, content.file.filename
  end

And when I check attachment.content it's still have old filename, so seems like nothing happens. So file physically renamed, but all instances of CW, like Attachment was not updated.

But when I'm trying to call attachment.save, I have an error: <ActiveModel::Error attribute=content, type=blank, options={}>.

What is the proper way to simply rename filename of CarrierWave file or to replace it with new filename?

1

There are 1 best solutions below

7
Amol Mohite On

To rename a file when updating the model, you can define a method in your model and use the #move_to method from CarrierWave.

For example:

class ModelName < ActiveRecord::Base
  mount_uploader :content, ContentUploader

  def rename_file
    if attribute_name.present? && attribute_name.file.present?
      new_filename = "new_filename.ext" # Set the desired new filename
      attribute_name.file.move_to(new_filename)
      attribute_name.file.filename = new_filename
    end
  end
end

In this example, new_filename.ext should be replaced with the desired new filename and extension.

In case of CarrierWave::SanitizedFile, you can refer below

file = CarrierWave::SanitizedFile.new
file.file.identifier = 'new_filename.ext'