Check If a File Was Uploaded with CarrierWave
Gaëtan Masson

Gaëtan Masson @gaetanm

About: Software writer fluent in Ruby.

Location:
Lille
Joined:
Apr 14, 2017

Check If a File Was Uploaded with CarrierWave

Publish Date: Aug 14 '18
5 0

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.

Comments 0 total

    Add comment