[Rails] [ActiveStorage] Find out if a particular user has an avatar

If a user does not have an avatar, an exception will be thrown when trying to access user.avatar. To prevent this, check if the file is attached in advance as user.avatar.attached?.

class User < ApplicationRecord
  has_one_attached :avatar
end

user = User.last
user.avatar.attached?
=> false

#Exception occurs when trying to access without attachment
user.avatar.url
=> Module::DelegationError: url delegated to attachment, but attachment is nil

#It can be avoided by doing the following
user.avatar.url if user.avatar.attached?
=> nil

Note: This commit is now handled so that it does not raise an exception https://github.com/rails/rails/commit/f002be148e1377709ed28b8e80c5db76ee2fa410

Postscript: Confirm that the above commit is included in v6.1.0.rc1

user = User.last
user.avatar.attached?
=> false

# Rails 6.1.0.Supported so that exception does not occur in rc1
user.avatar.url
=> nil

Reference URL

Rails Guide https://railsguides.jp/active_storage_overview.html

Recommended Posts

[Rails] [ActiveStorage] Find out if a particular user has an avatar
Rails6 Couldn't find User with'id' = sign_out and cannot log out
Rails6 OmniAuth activestorage Get user image
if ~ .length! = 0 Find an empty value
[Ruby on Rails] Error that Couldn't find User with ... after logging out