簡體   English   中英

在Rails應用程序中執行Ruby腳本

[英]Executing Ruby script in an Rails application

我可以在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 "<code or filename here>運行script/runner "<code or filename here> ”來運行腳本?運行程序腳本在沒有控制台的情況下在給定應用程序上下文中執行腳本。

您可以使其成為從環境繼承的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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM