This article shows how to duplicate a image flie already stored when using ActiveStorage.
環境情報&前提条件
- Ruby 3.2.1
- Rails 7.0.0
- 開発環境
- Docker使用
- DBのimage postgres:14-alpine
- 本番環境
- Herokuにデプロイ(stack heroku-22)
- Active Storageの画像の保存にはAmazon S3使用
解決したい内容
- 別レコードにすでに添付されている画像データを別レコードに複製して添付する。
- 新規添付時には以下のように添付できるが、既存レコードに添付済みの画像を複製して添付したい。
# 例)Productモデルのimage項目にasset内のdummy.jpgを添付する場合
product.image.attach(io: File.open(Rails.root.join("app/assets/images/dummy.jpg")),
filename: "dummy.jpg")
解決手順
-
product.image.blob
としてblob
メソッドを使用することで既存レコードの画像情報を取得可能
# 例)Productテーブルのid=1のレコードに添付されている画像を複製し、新規作成するレコードに添付し直す場合
# Productテーブルのid=1のレコードの取得
existing_product = Product.find(1)
# 既存レコードの画像を複製し、新規作成するレコードに再添付する
new_product = Product.new
new_product.image.attach(existing_product.image.blob)
# 新規レコードの保存
new_product.save
aa