-
Notifications
You must be signed in to change notification settings - Fork 1.7k
How To: Silently ignore missing files on destroy or overwrite
Saving a new file upload to a model it is mounted on attempts to clean up the previously-uploaded file. Destroying a model object also attempts to remove its mounted file. This is great and normally works. However, if for some reason the file it wants to delete does not exist, it raises a NotFound exception. The actual exception varies depending on what storage you are using -- e.g.: Fog::Storage::Rackspace::NotFound
if you're using Rackspace Cloud Files storage.
While it may be useful in catching other problems in your system, in production, you probably do not want to get stuck preventing model objects from being updated or deleted just because the file you want to delete was already deleted.
If you'd like to silently ignore these NotFound exceptions, you can do this simply by overriding the remove_avatar!
and remove_previously_stored_avatar
methods in your model class (replacing avatar
with the name of your mount column). The example below demonstrates doing this just to wrap the default implementation with a rescue block specifically for the Rackspace storage provider's exceptions. You could easily modify this to handle other type of exceptions.
class User < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
# Override to silently ignore trying to remove missing
# previous avatar when destroying a User.
def remove_avatar!
begin
super
rescue Fog::Storage::Rackspace::NotFound
end
end
# Override to silently ignore trying to remove missing
# previous avatar when saving a new one.
def remove_previously_stored_avatar
begin
super
rescue Fog::Storage::Rackspace::NotFound
@previous_model_for_avatar = nil
end
end
end
Or you can override it within AvatarUploader
:
class AvatarUploader < CarrierWave::Uploader::Base
# Override to silently ignore trying to remove missing
# previous avatar.
def remove!
begin
super
rescue Fog::Storage::Rackspace::NotFound
end
end
end
For the original discussion on this, see this Google Groups thread