1
votes

I am populating a rails app via he seeds file and wanted to attach a picture to each account but it is not working and I can't figure out why.

I read the ActiveStorage documentation and tried applying the solutions that I found on two different answers here on Stackoverflow to no avail, I can

I'm getting the following error:

> Clearing Database...
> Creating users...
rails aborted!
ActiveStorage::IntegrityError: ActiveStorage::IntegrityError
/mnt/c/Users/pedro/code/ruby-projects/tinder-clone/db/seeds.rb:20:in `block in <main>'
/mnt/c/Users/pedro/code/ruby-projects/tinder-clone/db/seeds.rb:12:in `times'
/mnt/c/Users/pedro/code/ruby-projects/tinder-clone/db/seeds.rb:12:in `<main>'
/mnt/c/Users/pedro/code/ruby-projects/tinder-clone/bin/rails:9:in `<top (required)>'
/mnt/c/Users/pedro/code/ruby-projects/tinder-clone/bin/spring:15:in `<top (required)>'
./bin/rails:3:in `load'
./bin/rails:3:in `<main>'
Tasks: TOP => db:seed

This is my seed file:

require 'faker'
require "open-uri"


puts "> Clearing Database..."
Account.destroy_all

puts "> Creating users..."

FILE = File.open('app/assets/images/portrait.jpg')

15.times do 
  account = Account.create(
    first_name: Faker::Name.first_name,
    last_name: Faker::Name.last_name,
    username: Faker::Games::Witcher.monster,
    email: Faker::Internet.email,
    password: "123456",
  )
  account.images.attach(io: FILE, filename: 'person.jpg', content_type: 'image/jpg')

end

puts "> Done!"

And here is my model:

class Account < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many_attached :images

end

I appreciate your help, thanks!

1

1 Answers

0
votes

ActiveStorage::IntegrityError is raised when uploaded or downloaded data is corrupted ( not match a precomputed checksum ). As you are using faker gem, I sugest you do something like this:


url = Faker::Avatar.image(slug: 'my-own-slug', size: '250x250')
filename = File.basename(URI.parse(url).path)
file = URI.open(url)

15.times do 
  account = Account.create(
    first_name: Faker::Name.first_name,
    last_name: Faker::Name.last_name,
    username: Faker::Games::Witcher.monster,
    email: Faker::Internet.email,
    password: "123456",
  )
  account.images.attach(io: file, filename: filename)
end