model - Rails: How do I run a before_save only if certain conditions are met? -
i have before_save method call renames 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
that method part of item
model.
that works great when create new item or need update image associated item...but problem if need update item not image, randomize_file_name
method still gets run , renames file in database (though not file itself, obviously).
so, i'm thinking need figure out way run randomize_file_name
if file included in form submission...but i'm not sure how pull off.
use dirty objects.
before_save :randomize_file_name def randomize_file_name # assuming field holds name # 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
Comments
Post a Comment