I have hard time with uploading seeds from YAML file- everything works fine until try to upload post without image(image: nil)
#seeds.rb
posts_file = Rails.root.join('db', 'seeds', 'fixtures', 'posts.yml')
posts = YAML::load_file(posts_file)
images_path = Rails.root.join('db', 'seeds', 'fixtures', 'images')
posts.each do |post|
Post.create(
title: post['title'],
content: post['content'],
created_at: post['created_at'],
updated_at: post['updated_at'],
deleted_at: post['deleted_at'],
post_img: File.open("#{images_path}#{post['post_img']}")
)
end
and YAML file:
-
title: 'Title1'
content: 'some content for post'
created_at:
updated_at:
deleted_at:
post_img: '/image1jpg'
-
title: 'Title 2'
content: 'some content for post'
created_at:
updated_at:
deleted_at:
post_img:
If I fill both post_img fields it works fine, but when one of these is empty get this error:
Errno::EISDIR: Is a directory
which means that it reads whole images folder. How to find a way to avoid this error?
The problem is that when post_img
is empty/nil, File.open("#{images_path}#{post['post_img']}")
is a directory (images_path
) instead of a file, as the error message says. You can do something like:
file = File.open("#{images_path}#{post['post_img']}") if post['post_img'].present?
Post.create(
title: post['title'],
content: post['content'],
created_at: post['created_at'],
updated_at: post['updated_at'],
deleted_at: post['deleted_at'],
post_img: file
)
This will create a post with a nil image in case post_img
is empty/nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With