在 Rails 中从 Amazon S3 播种多个图像附件

Seeding multiple image attachments from Amazon S3 in Rails

我正在尝试将多个图像附件播种到一个模型中。我一直在使用 ,但我仍然有点卡住了,因为我的目标有所不同,因为:

  1. 我正在尝试将多个图像附加到模型中的每个对象(我播种)
  2. 我想从我的 S3 存储桶中检索这些图像并将它们附加到对象(这可能吗?)

这是我的 seed.rb:

shirt = Item.create(name:"Basic Shirt",price:19.99)
skirt = Item.create(name:"Basic Skirt",price:29.99)
sweater = Item.create(name:"Basic Sweater",price:39.99)
kid_hood = Item.create(name:"Basic Kid Hoodie",price:19.99)

# somehow attach images here?

我正在使用 aws-sdk-s3 gem 将 Active Storage 连接到我的 S3 存储桶。请告诉我是否需要任何其他文件才能查看。我会很乐意编辑此 post 以包含它。

ActiveStorage 在纯字节流上工作,因此您可以下载文件(例如使用 open-uri)并将流指定为附件的内容。

假设您有以下内容(如果不同则进行调整)

class Item < ApplicationRecord
  has_one_attached :photo
end

您可以将种子设为:

require 'open-uri'

shirt = Item.create(name:"Basic Shirt",price:19.99)
shirt.photo.attach(io: open('your-s3-nonexpiring-url'), filename: 'foo.bar')

# ...