我很难从YAML文件上传种子-一切都很好,直到尝试上传没有图像的帖子(图像: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
和YAML文件:
-
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:
如果我同时填写两个post_img字段,它可以正常工作,但当其中一个字段为空时,会出现以下错误:
Errno::EISDIR:是一个目录
这意味着它读取整个图像文件夹。如何找到避免此错误的方法?
问题是,当post_img
为空/nil时,File.open("#{images_path}#{post['post_img']}")
是一个目录(images_path
(,而不是文件,正如错误消息所说。你可以做一些类似的事情:
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
)
这将在post_img
为空/nil的情况下创建一个具有nil图像的帖子。