Carrierwave filename keeps changing on update_attributes
Asked Answered
P

1

6

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?

Phillipphillipe answered 30/3, 2014 at 18:59 Comment(2)
filename value in DB is still being changed every time with a new filename or existing file name? What is the original file name before updating? Do you mean that 1396206630_1f288be4.jpg is a new file name?Apotheosize
With new file name. Although no new file was uploaded.Phillipphillipe
M
7

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
Mattress answered 13/5, 2014 at 2:50 Comment(1)
This should be the accepted answer. Worked for me. Nonetheless it's weird that carrierwave fires this filename method every time the record gets updated.Chorus

© 2022 - 2024 — McMap. All rights reserved.