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
Rails Guide https://railsguides.jp/active_storage_overview.html
Recommended Posts