Rails: How do I run a before_save only if certain conditions are met?
Posted
by Shpigford
on Stack Overflow
See other posts from Stack Overflow
or by Shpigford
Published on 2010-04-28T18:08:12Z
Indexed on
2010/04/28
18:17 UTC
Read the original article
Hit count: 224
ruby-on-rails
|model
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
That method is part of my Item
model.
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).
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.
© Stack Overflow or respective owner