DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

GaΓ«tan Masson
GaΓ«tan Masson

Posted on • Updated on

Check If a File Was Uploaded with CarrierWave

TL;DR

Use:

user.avatar.present?
Enter fullscreen mode Exit fullscreen mode

NOT:

user.avatar.file.nil?
Enter fullscreen mode Exit fullscreen mode

Details

When you want to check if a file is attached to your model, the official Carrierwave documentation says:

Note: u.avatar will never return nil, even if there is no photo associated to it. To check if a photo was saved to the model, use u.avatar.file.nil? instead.

That's fine, it works. BUT! If you are using a cloud storage service like Amazon S3, each time the line file.nil? will be executed, a request will be sent to the cloud storage to check the presence of the file. As you guess, it's not cool because it can make your app slower.

The solution is simply to use u.avatar.present?. This way, no more external call.

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.