DEV Community

Gaëtan Masson
Gaëtan Masson

Posted on • Edited on

3 2

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay