简体   繁体   中英

Adding image to seed database in rails 5.2 active storage

Just trying to add an image to my seed file. Having a little issue when trying to add using the new active storage in Rails 5.2

Can anyone spot what's happening. Here is the code followed by error in db. Thanks.

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')

end

Error:

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

You are passing a directory not a file in this code:

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

If your image path is: /Users/bradley/Dart.png . Then you need to change your code:

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

However I would not recommend to use absolute paths in your project even if it was only for seeds. You can add the image to your rails project and use relative path to your project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM