无法在Rake任务中找到数据文件

时间:2016-11-03 03:02:43

标签: ruby-on-rails rake rake-task

我想使用临时rake文件为生产环境播种一些数据。

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

运行rake任务会产生以下错误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'

下面的代码片段是我的佣金任务,

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

2 个答案:

答案 0 :(得分:0)

文件路径不应使用相对路径

cell.textLabel?.text = values[indexPath.row]

答案 1 :(得分:0)

你可以使用这样的东西:

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