2009-08-18 77 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 

然后运行。它可以被称为任何你想要的。