Search code examples
ruby-on-railsamazon-s3rails-activestorage

Seeding multiple image attachments from Amazon S3 in Rails


I am trying to seed multiple image attachments to a model. I have been using this link but I am still sort of stuck since what I aim to do differs a little since:

  1. I am trying to attach multiple images to each object (which I seed) in the model
  2. I want to retrieve these images from my S3 bucket and attach them to the objects (is this possible?)

Here's my 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?

I am using the aws-sdk-s3 gem in order to connect Active Storage to my S3 bucket. Please tell me if any additional files are needed for viewing. I will happily edit this post to include it.


Solution

  • ActiveStorage work on plain byte streams, so you can download the file (using open-uri for instance) and assign the stream as the content of the attachment.

    Assuming you have the following (adapt if different)

    class Item < ApplicationRecord
      has_one_attached :photo
    end
    

    you can have your seeds as:

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