Check & confirm that a file is attached to CarrierWave
CarrierWave is an old juggernaut of a Ruby GEM. It is still around in 2021, primarily on Ruby on Rails projects that predate ActiveStorage, including my website. Reviewing a PR, I noticed a common mistake made with newbies to CarrerWave when checking if a file was attached to a model.
Confirm File Attachment
Almost any project that uses CarrierWave or any other library like ActiveStorage and PaperClip will eventually need to check if a file was attached to the model. You can do this with:
class User < ApplicationRecord
mount_uploader :avatar, AvatarUploader
end
user = User.first
user.avatar.present? # Good practice 👍
Bad Practice
user.avatar.file.nil? # Concerning 😨
In my particular instance, the software engineer had used user.avatar.file.nil?
for the check. But if you are using cloud storage like Amazon S3, CarrierWave will perform an API call. The API call will significantly slow down your application.
If you are checking for the existence of the file, you will need to do a nil check (ex: user.avatar.file.nil?
).
What doesn't work
user.avatar.nil? # You alright? 👀
It is important to remember that the mounted CarrierWave filed will never return nil
regardless if a file is uploaded or not. So make sure you don't do user.avatar.nil?
.
About the Author
Ziyan Junaideen -
Ziyan is an expert Ruby on Rails web developer with 8 years of experience specializing in SaaS applications. He spends his free time he writes blogs, drawing on his iPad, shoots photos.