This article shows how to judge whether to be arleady attached an image when using ActiveStorage.
環境情報&前提条件
- Ruby 3.2.1
- Rails 7.0.0
解決したい内容
- ActiveStorageで画像を添付する。レコードにすでに画像が添付済みかの判定を行いたい。
-
nil?
で判定すると常時false
が返ってくるので、一見画像が添付されているように見える。しかし、画像の実体をうまく取得できない。
解決手順
- nil判定ではなく、
attached?
メソッドを使用して判定する。- 補足:画像の実体は
blob
レコードなので実体を見たい場合はimage.blob
のようにして参照を1段階深くたどる必要がある。
- 補足:画像の実体は
# 例)Userモデルのimage項目に画像を添付する
# nil判定では添付済み判定を正しく行えない。画像自体は未添付でもnil?はfalseを返す。
# id=1のレコードのimageには画像添付されていないとする
user = User.find(1)
# 画像自体は未添付(=blobレコードが存在しない)でもActiveStorageのレコードは紐づいているのでnil判定が使えない。
user.image
=> <ActiveStorage::Attached::One:0x0000ffff7d63c450>
user.image.nil?
=> false
# 解決策:attachedメソッドを使用して判定する。
user.image.attached?
=> true
# 補足:画像が添付されている場合は、blobレコードが添付される。
# id=2のレコードにはimageが添付されているとする
attached_user = User.find(2)
attached_user.image.nil?
=> false
attached_user.image.blob
=> <ActiveStorage::Blob:0x0000ffff80499898>
attached_user.image.blob.nil?
=> false