0

我正在编写一个 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 类或类似的东西。

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

更新:


基于 Phillip Hallstrom 的回答

我更改了顶行以加载环境

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

然后尝试 rake import_channels 并得到这个错误:

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

1 回答 1

1

您需要在运行 Rake 任务之前加载环境。我不熟悉那里的多个任务名称选项,但举个简单的例子,你会想要这个:

task : import_channels => :environment do
于 2013-09-29T18:04:44.650 回答