carrierwaveuploader / carrierwave

Classier solution for file uploads for Rails, Sinatra and other Ruby web frameworks
https://github.com/carrierwaveuploader/carrierwave
8.78k stars 1.66k forks source link

filename on update #2731

Closed tigus closed 2 months ago

tigus commented 8 months ago

I have an issue after upgrading to carrierwave 3 (from 2.2) I wish to keep the previous name of my image on update, but it doesn't seem possible anymore.

I have a simple form to update an image of my img model: <%= file_field_tag "asset-#{id}-img", class: "form-control field_img" %>

And then, in my controller, I make my update:

@asset.update(asset_params)

I use this function to setup the filename:

def filename
        if original_filename.present?
            if model.new_record?
                filename = File.basename(original_filename, '.*')
                "#{filename}#{filename.match(/_[0-9]{3}$/) ? '' : random_id}.#{file.extension}"
            else
                model['img']
            end
        end
    end

but, while carrierwave 2.2 returned the original name (saved in DB), model['img'] now returns a new name...

So I tried this code:

    def filename
        if original_filename.present?
            if model.new_record?
                filename = File.basename(original_filename, '.*')
                "#{filename}#{filename.match(/_[0-9]{3}$/) ? '' : random_id}.#{file.extension}"
            else
                model['img'] = model.img_was
            end
        end
    end

but it still doesn't work as, if my name was original_123.jpg, I get original_123(2).jpg...

Thanks in advance for your help!

mshibuya commented 2 months ago

As I wrote in this comment, you can choose to override #deduplicated_filename to stop the deduplication:

  def deduplicated_filename
    filename
  end

but I don't recommend this, the reason is in the comment.