2009-08-18 54 views
3

我可以在控制檯中爲我的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文件和執行將無法正常工作。

任何幫助將不勝感激:)

回答

5

爲什麼不使用script/runner "<code or filename here>?運行腳本?運行程序腳本在給定應用程序上下文中執行腳本而不需要控制檯。

+0

haha​​ Rails太棒了;) 謝謝! – b1gtuna 2009-08-18 15:34:14

+1

更好的解決方案是有一個rake任務。 – 2009-08-18 22:27:18

+2

在3.0+中,使用'rails runner path/to/script'。注意:腳本的路徑與您的項目根目錄相關,而不是您的工作目錄。 – 2012-08-28 20:20:13

1

您需要調用腳本中的rails環境。

嘗試頂部的你加入這個文件:

RAILS_ENV = ARGV[0] || "production" 
require File.join(File.dirname(__FILE__), *%w[.. config environment]) 
# assumes script is placed one level below the root of the application 
# second parameter is the relative path to the environment directory of your rails app 
2

你可以讓它成爲一個從環境繼承的rake任務。它放入的lib /任務/ your_task.rake:它使用rake your_task

task :your_task => :environment do 
    # code goes here 
end 

然後運行。它可以被稱爲任何你想要的。

相關問題