在Rails应用程序中执行Ruby脚本

我可以在控制台中为我的Rails应用程序运行以下命令,并将CSV文件导入我的数据库。

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文件中,执行就不起作用。

任何帮助将永远受到赞赏:)

为什么不使用script/runner "运行script/runner " ?”来运行脚本?运行脚本在给定应用程序上下文中执行脚本而不需要控制台。

你可以把它作为一个从环境inheritance的rake任务。 将它放入lib / tasks / your_task.rake

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

然后使用rake your_task运行它。 它可以被称为你想要的任何东西。

您需要在脚本中调用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