如何将 CSV 文件作为耙子任务读取并实例化模型类?- 获得活动记录连接错误



我正在编写一个Ruby on Rails应用程序,该应用程序具有可以解析CSV文件的Rake任务。

这是代码:

 desc "Import Channels into DBn 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 任务创建通道对象。

我的假设是,也许在某个文件夹/层次结构之外,应用程序无法访问 ActiveRecord::Base 类或类似的东西。

关于如何完成这项工作的任何建议?

更新:


利普·霍尔斯特罗姆(Phillip Hallstrom)的答案

我更改了顶行以加载环境

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

然后尝试import_channels耙子并得到此错误:

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

您需要在运行 Rake 任务之前加载环境。我不熟悉您的多个任务名称选项,但对于一个简单的示例,您需要这个:

task : import_channels => :environment do

最新更新