如何避免 Errno::EISDIR: 目录 - 在 运行 种子迁移时读取?

How to avoid Errno::EISDIR: Is a directory - read when run seed migration?

我很难从 YAML 文件上传种子 - 一切正常,直到尝试上传 post 没有图像(图像:无)

#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: Is a directory

这意味着它读取整个图像文件夹。如何找到避免此错误的方法?

问题是,当 post_img 是 empty/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 是 empty/nil。

,这将创建一个没有图像的 post