0
0

Rails7 ActiveStorage レコードに添付済みの画像を複製して別レコードに添付する

Last updated at Posted at 2023-10-01

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

参考記事

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