将图像添加到 rails 中的种子数据库 5.2 活动存储

Adding image to seed database in rails 5.2 active storage

只是想将图像添加到我的种子文件中。在 Rails 5.2

中尝试使用新的活动存储进行添加时遇到一点问题

任何人都可以发现发生了什么。这是代码后跟数据库中的错误。谢谢。

25.times do
temp = Post.create([{
    title: Faker::Book.unique.title,
    content: Faker::Lorem.paragraphs(rand(100..200)).join('\n'),
    category_id: rand(1..5),
    user_id: 1,
    status: 1,
    recommended: [true, false].sample,
    excerpt: Faker::Lorem.paragraph(10) 
        }])
  puts Post.first.featured_image
  temp.first.featured_image.attach(io: File.open('/Users/bradley/'), filename: 'Dart.png', content_type: 'image/png')

结束

错误:

#<ActiveStorage::Attached::One:0x00007fb672434448>
rake aborted!
Errno::EISDIR: Is a directory @ io_fread - /Users/bradley/

您在此代码中传递的是目录而不是文件:

File.open('/Users/bradley/')

如果你的图片路径是:/Users/bradley/Dart.png。那么你需要更改你的代码:

File.open('/Users/bradley/Dart.png')

但是我不建议在你的项目中使用绝对路径,即使它只是用于种子。您可以将图像添加到您的 rails 项目并使用项目的相对路径。