簡體   English   中英

如何讀取CSV文件作為rake任務並實例化模型類? -獲取ActiveRecord連接錯誤

[英]How can I read a CSV file as a rake task and instantiate a model class? - getting ActiveRecord connection error

我正在編寫一個Ruby on Rails應用程序,該應用程序具有可以解析CSV文件的Rake任務。

這是代碼:

 desc "Import Channels into DB\n Usage: rake channel_import"
 task :import_channels, :path_to_channel_list do |t, args|

 require "#{Rails.root}/app/models/channel"
 require "csv"
 filePath = args.path_to_channel_list
 puts "Filepath received = #{filePath}"
csv = CSV.read("#{filePath}", :encoding => 'windows-1251:utf-8')
  csv.each_with_index do |row, i|
 if [0].include?(i)
      puts "Skipping over row #{i}"
      next
     end
     if(row.nil?)
      puts "row[#{i}] was nil"
     else
channelName = nil
      classif = nil
      owner = nil
      channelName = row[0].force_encoding('UTF-8')
      classif = row[1].force_encoding('UTF-8')
      owner = row[2].force_encoding('UTF-8') 
      if (channelName.nil?)
        puts "Channel name for row #{i} was nil"
        #add entry to Log file or errors database
        next #skip this row of the csv file and go to next row
      else
        channel_hash = Hash.new("name" =>"#{channelName}", "classification" => "#{classif}", "owner" => "#{owner}" )

      end
       puts "\nChannel Name = #{channelName}\nClassification = #{classif}\n Ownership = #{owner}"
      #If channel name exists in the Database, update it
      xisting_channel = nil
      xisting_channel = Channel.find_by channel_name: '#{channelName}'
      if(xisting_channel.nil?)
          #create a new channel
      @new_channel = Channel.create(channel_hash) 
      puts "Inserted....#{@new_channel.inspect}"
      else
          #update existing channel
          Channel.update(xisting_channel.id, :classification => "#{classif}", :ownership => "#{owner}" )
          puts "Updated...."
          puts "channel_hash = #{channel_hash.inspect} "
      end#end if/else

  end#end if/else

 end #end CSV.each


 end

當我運行此代碼時,出現以下錯誤消息:

 MRMIOMP0903:am AM$ rake import_channels[/XXXXXXXX/Channellist.csv]
 Filepath received = /XXXXXXX/Channellist.csv
 Skipping over row 0

 Channel Name = APTN HD+
 Classification = Specialty
 Ownership = Aboriginal Peoples Television Network
 rake aborted!
 ActiveRecord::ConnectionNotEstablished

我嘗試使用IRB創建Channel對象,並且效果很好。 數據庫已創建,我正在使用MySQL WorkBench看到它。 所有表都在那里,但是,我無法從Rake任務中創建Channel對象。

我的假設是,也許在某個文件夾/層次結構之外,該應用無法訪問ActiveRecord :: Base類或類似的東西。

關於如何進行這項工作的任何建議?

更新:


根據菲利普·霍爾斯特倫的答案

我更改了頂行以加載環境

 task   :import_channels => :environment do|t, args|

然后嘗試rake import_channels並得到此錯誤:

rake aborted!
undefined method `safe_constantize' for #<Hash:0x007fbeacd89920>

您需要在運行Rake任務之前加載環境。 我不熟悉您的多個任務名稱選項,但是對於一個簡單的示例,您需要這樣做:

task : import_channels => :environment do

暫無
暫無

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

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