2016-11-03 52 views
0

我想使用生產環境的臨時rake文件播種一些數據。在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' 

代碼段是我的rake任務,

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 

回答

0

你可以使用這樣的事情:

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

我傾向於避免硬編碼路徑。 –

0

文件路徑不應該使用相對路徑

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