Carrierwave文件名在update_attributes上不断变化 [英] Carrierwave filename keeps changing on update_attributes

查看:80
本文介绍了Carrierwave文件名在update_attributes上不断变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有公司模型,公司已安装了载波上传器徽标.

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

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

图片上传正常,但是update_attributes出现问题.当用户只想更新公司的描述或标题,而又不想上载新图像时,DB中的文件名值仍然每次都在更改.这是一个简单的示例:

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?

推荐答案

我经历了同样的事情,并发现,除非出现original_filename,否则上载程序类的filename方法不应设置新的文件名. CarrierWave具有有关文件名的相关Wiki页面,它不能直接解决此问题,但足以提供线索.

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.

例如,

每次更新模型时,此代码都会更改文件名字段.

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

但是,这种额外的if语句阻止了以前的行为.

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

这篇关于Carrierwave文件名在update_attributes上不断变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆