我很难从YAML文件中上传种子-一切正常,直到尝试上传不包含图片的帖子为止(图片:无)
#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:是目录
这意味着它将读取整个图像文件夹。如何找到避免这种错误的方法?
答案 0 :(得分:0)
问题是,如错误消息所示,当post_img
为空/无时,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
为空/无的情况下,这将创建带有零图像的帖子。