【问题标题】:Rails Active Storage Error when attempting to attach photo on seed file尝试在种子文件上附加照片时出现 Rails Active Storage 错误
【发布时间】:2020-08-26 20:18:32
【问题描述】:

我正在通过他的种子文件填充一个 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

感谢您的帮助,谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby rails-activestorage


    【解决方案1】:

    ActiveStorage::IntegrityError 在上传或下载的数据损坏时引发(与预先计算的校验和不匹配)。 当您使用faker gem时,我建议您执行以下操作:

    
    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
    
    

    【讨论】:

    • 嗨,赫利奥。不幸的是,它没有解决错误,但我很感激帮助。我将继续尝试并弄清楚。干杯。
    猜你喜欢
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2020-11-04
    • 2022-11-11
    • 2015-11-14
    • 2014-07-28
    相关资源
    最近更新 更多