问题描述
我正在通过他的种子文件填充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。 当您使用假冒宝石时,我建议您执行以下操作:
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