本文介绍了Rails:仅在满足某些条件的情况下,才如何运行before_save?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个调用before_save的方法,该方法重命名了上载的图像.

I have a before_save method that I call that renames an uploaded image.

before_save :randomize_file_name

def randomize_file_name
  extension = File.extname(screen_file_name).downcase
  key = ActiveSupport::SecureRandom.hex(8)
  self.screen.instance_write(:file_name, "#{key}#{extension}")
end

该方法是我的Item模型的一部分.

That method is part of my Item model.

当我创建一个新项目或需要更新与该项目相关的图像时效果很好...但是问题是,如果我需要更新一个项目而不是图像,则randomize_file_name方法仍然可以运行并重命名数据库中的文件(显然不是文件本身).

That works great when I create a new item or need to update the image associated with an item...but the problem is that if I need to update an item but NOT the image, the randomize_file_name method still gets run and renames the file in the database (though not the file itself, obviously).

因此,我想我需要找出一种仅在表单提交中包含文件的情况下运行randomize_file_name的方法...但是我不确定如何实现.

So, I'm thinking I need to figure out a way to only run randomize_file_name if a file is included in the form submission...but I'm not sure how to pull that off.

推荐答案

使用脏对象.

before_save :randomize_file_name

def randomize_file_name
  # assuming the field that holds the name
  # is called screen_file_name
  if screen_file_name_changed?
    extension = File.extname(screen_file_name).downcase
    key = ActiveSupport::SecureRandom.hex(8)
    self.screen.instance_write(:file_name, "#{key}#{extension}")
  end
end

这篇关于Rails:仅在满足某些条件的情况下,才如何运行before_save?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:48