我可以在控制台中为我的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