Swann
Swann

Reputation: 2473

Duplicate entries when trying to seed image on ActiveStorage

I am new to the Ruby on Rails ecosystem so might question might be really trivial.

I have set up an Active Storage on one of my model

class Sedcard < ApplicationRecord
  has_many_attached :photos
end

And I simply want to seed data with Faker in it like so:

require 'faker'

Sedcard.destroy_all
20.times do |_i|
  sedcard = Sedcard.create!(
    showname: Faker::Name.female_first_name,
    description: Faker::Lorem.paragraph(10),
    phone: Faker::PhoneNumber.cell_phone,
    birthdate: Faker::Date.birthday(18, 40),
    gender: Sedcard.genders[:female],
    is_active: Faker::Boolean.boolean
  )

  index = Faker::Number.unique.between(1, 99)
  image = open("https://randomuser.me/api/portraits/women/#{index}.jpg")
  sedcard.photos.attach(io: image, filename: "avatar#{index}.jpg", content_type: 'image/png')
end

The problem is that some of these records end up with multiple photos attached to them, could be 5 or 10.

Most records are seeded well, they have only one photo associated, but the ones with multiple photos all follow the same pattern, they are all seeded with the exact same images.

Upvotes: 0

Views: 264

Answers (2)

Swann
Swann

Reputation: 2473

I found the problem myself.

I was using UUID as my model's primary key which is not natively compatible with ActiveStorage. Thus, I more or less followed the instructions here

Upvotes: 1

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

You need to purge the attachments.

Try adding this snippet before destroyingthe Sedcard's

Sedcard.all.each{ |s| s.photos.purge }

Ref: https://edgeguides.rubyonrails.org/active_storage_overview.html#removing-files

Upvotes: 0

Related Questions