从CSV导入时导轨实例变量

时间:2015-03-31 09:09:18

标签: ruby ruby-on-rails-3.2 rake

以下rake任务完美运行

  task :load_scadenze_data  => :environment do
    require 'csv'

    CSV.foreach("_private/scadenze.tsv", :col_sep => "\t", headers: true) do |row|

      begin
       @supplier =  Supplier.find_by_code(row[2])
       @scadenza = row[0].to_date
       if (@scadenza <= Date.today)
         @cweek_payment = 0
       else
         @cweek_payment = @scadenza.cweek
       end
       Scadenza.create(
          :data_scadenza  => row[0],
          :supplier_id => @supplier.id
       )
      rescue StandardError => e
        puts "Error importing row because '#{e.message}'"
        puts row
      end
    end
  end

然而,当将其转换为模型方法时,

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|

  begin
   @supplier =  Supplier.find_by_code(row[2])
   @scadenza = row[0].to_date
   if (@scadenza <= Date.today)
     @cweek_payment = 0
   else
     @cweek_payment = @scadenza.cweek
   end
   Scadenza.create(
      :data_scadenza  => row[0],
      :supplier_id => @supplier.id
   )
  end   
end

记录未导入,因为 Error importing row because 'Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id'

因此,rails框架的行为方式不同。处理模型方法的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

在您的“rake”版本的脚本中,您正在解析CSV:

CSV.foreach("_private/scadenze.tsv", :col_sep => "\t", headers: true)

但是在“模型”版本中,缺少:col_sep选项 - 可能是错误地解码了CSV,并且它在row[2]中存储了无效值,因此无法找到{{1} }}?