Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 620
pfc Avatar asked Sep 16 '25 02:09

pfc


1 Answers

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.

like image 120
Ana María Martínez Gómez Avatar answered Sep 19 '25 06:09

Ana María Martínez Gómez