我可以在控制檯中爲我的Rails應用程序運行以下命令並將CSV文件導入到我的數據庫中。在Rails應用程序中執行Ruby腳本
require 'csv'
# row will be an array with the fields in the order they appear in the file
CSV.open('myfile.csv', 'r') do |row|
# assuming the fields in the CSV file are in order npa, nxxFrom, nxxTo, trnk
# create and save a Trunk model for each row
Trunk.create!(:npa => row[0], :nxxFrom => row[1], :nxxTo => row[2], :trnk => row[3])
end
但是我想通過爲它創建一個腳本來簡化這個過程。問題是我不知道如何編寫特定於應用程序的腳本。爲了使上面的命令來運行,我需要通過下面的應用程序文件夾啓動控制檯:
ruby script/console
所以,簡單地複製/粘貼命令到.RB文件和執行將無法正常工作。
任何幫助將不勝感激:)
haha Rails太棒了;) 謝謝! – b1gtuna 2009-08-18 15:34:14
更好的解決方案是有一個rake任務。 – 2009-08-18 22:27:18
在3.0+中,使用'rails runner path/to/script'。注意:腳本的路徑與您的項目根目錄相關,而不是您的工作目錄。 – 2012-08-28 20:20:13