2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RailsのオブジェクトをActiveStorageの画像ごとクローンする

2
Posted at

ActiveStorageの画像がそのまま代入できなかった

  def duplicate
    @product = Product.find_by(id: params[:id])
    @product.product_options

    @duplicated_product = @product.deep_dup
    @duplicated_product.product_options = @product.product_options
    @duplicated_product.image = @product.image
    @duplicated_product.save!
  end

以下のように怒られた

Could not find or build blob: expected attachable, got #<ActiveStorage::Attached::...

解決策

いったんopenでダウンロードしてから、URLで再度attachしたらいけた

  def duplicate
    @product = Product.find_by(id: params[:id])
    @product.product_options

    @duplicated_product = @product.deep_dup
    @duplicated_product.product_options = @product.product_options
    downloaded_image = open(@product.image.service_url)
    @duplicated_product.image.attach(io: downloaded_image  , filename: "foo.jpg")
    @duplicated_product.save!
  end

🤔より良い方法があったらしりたいです。。。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?