尝试将照片附加到种子文件时发生Rails活动存储错误



我正在通过种子文件填充rails应用程序,并想为每个帐户附加一张图片,但它不起作用,我不知道为什么。

我阅读了ActiveStorage文档,并尝试应用我在Stackoverflow上的两个不同答案上找到的解决方案,但都无济于事,我可以

我得到以下错误:

> 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

这是我的种子文件:

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!"

这是我的模型:

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

我感谢你的帮助,谢谢!

ActiveStorage::IntegrityError在上载或下载的数据损坏(与预先计算的校验和不匹配(时引发。当你使用faker宝石时,我建议你这样做:


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

最新更新