XYZ
XYZ

Reputation: 27397

Could not find data file in a Rake task

I would like to seed some data using a temp rake file for production env.

.
├── assets
└── tasks
    └── temporary
        ├── languages.csv
        └── languages.rake

Running the rake task produces the following error, No such file or directory.

Language Database Initialization Completed
rake aborted!
Errno::ENOENT: No such file or directory @ rb_sysopen - ./languages.csv
/home/li-xinyang/Desktop/XX_OpenNB/lib/tasks/temporary/languages.rake:7:in `read'

Code snippet below is my rake task,

require 'csv'

namespace :languages do
  desc 'Seed initial languages data with language & code'
  task init_data: :environment do
    ActiveRecord::Base.transaction do
      csv_str = File.read('./languages.csv')
      csv = CSV.new(csv_str).to_a
      csv.each do |lan_set|
        lan_code = lan_set[0]
        lan_str = lan_set[1]
        Language.new(language: lan_str, code: lan_code).save
        print '.'
      end
    end
    puts 'Language Database Initialization Completed'
  end
end

Upvotes: 0

Views: 500

Answers (2)

sa77
sa77

Reputation: 3603

you could use something like this:

csv_str = File.read("#{Rails.root}/app/tasks/temporary/languages.csv")

Upvotes: 2

XYZ
XYZ

Reputation: 27397

The file path should not use relative path

  csv_path = File.expand_path('languages.csv', File.dirname(__FILE__))
  csv_str = File.read(csv_path)

Upvotes: 0

Related Questions