0
0

Rails7 ActiveStorage レコードに画像添付済みかの判定を行う

Last updated at Posted at 2023-10-01

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0