Carrierwave filename keeps changing on update_attr

2019-02-13 21:50发布

问题:

I have model Company and company has mounted carrierwave uploader Logo.

class Company < ActiveRecord::Base
  mount_uploader :logo, LogoUploader

Images upload works, but I have an issue with update_attributes. When user wants to update only description or title of the company, but not to upload new image - filename value in DB is still being changed every time. Here is a simple example:

1.9.3-p545 :004 > a = Company.last
1.9.3-p545 :005 > a.update_attributes(:title => "test title 2")
 (0.4ms)  BEGIN
  Company Exists (0.9ms)  SELECT 1 AS one FROM `companies` WHERE (`companies`.`title` = BINARY 'test title 2' AND `companies`.`id` != 37) LIMIT 1
  Company Load (0.7ms)  SELECT `companies`.* FROM `companies` WHERE `companies`.`id` = 37 LIMIT 1
   (0.7ms)  UPDATE `companies` SET `title` = 'test title 2', `logo` = '1396206630_1f288be4.jpg', `updated_at` = '2014-03-30 19:10:30' WHERE `companies`.`id` = 37
   (8.1ms)  COMMIT
 => true 

Why logo is being updated here with new value even the new value was not given? How to avoid this?

回答1:

I experienced the same and figured it out that an uploader class' filename method should not set a new filename unless original_filename presents. CarrierWave has a relevant wiki page about filename which doesn't directly address this issue, but is enough to get a clue.

For example,

This code changes the filename field every time the model is updated.

class SampleUploader < CarrierWave::Uploader::Base
  def filename
    "#{Time.now.strftime('%Y%m%d%H%M%S')}.jpg"
  end
end

However this extra if statement prevents the former behaviour.

class SampleUploader < CarrierWave::Uploader::Base
  def filename
    "#{Time.now.strftime('%Y%m%d%H%M%S')}.jpg" if original_filename.present?
  end
end