【问题标题】:After importing a csv file, extra rows are being created in my sqlite db table导入 csv 文件后,在我的 sqlite db 表中创建了额外的行
【发布时间】:2012-10-30 13:01:11
【问题描述】:

我正在通过 rake 任务将 17 个 csv 文件导入我的应用程序。其他文件将正常导入并且不会创建额外的行,但由于某种原因,该文件在我的数据库中创建了大约 60 个空行。我尝试导入的信息运行良好,并且以应有的方式与其适当的表相关联。因此,如果您要使用该应用程序,一切都会正常运行,但会弄乱我的桌子。

例如,我将 2 行导入到表中,并且在创建这两行之后,紧随其后的是 58 个空白行。有没有人对我如何使用条件语句来防止这种情况发生有任何建议,请具体说明我在这方面还是比较新的。谢谢

这是我的代码:

require 'csv'

namespace :import_mat_lists_csv do

task :create_mat_lists => :environment do
    puts "Import Material List"

    csv_text = File.read('c:/rails/thumb/costrecovery/lib/csv_import/mat_lists.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each_with_index do |row,index|
        row = row.to_hash.with_indifferent_access
        MatList.create!(row.to_hash.symbolize_keys)
        matlist = MatList.last
        if @report_incident_hash.key?(matlist.report_nr)
            matlist.incident_id = "#{@report_incident_hash[matlist.report_nr]}"
        end

        #matlist.timesheet_id = @timesheet_id_array[index]
        matlist.save
    end
    end
  end

【问题讨论】:

  • 感谢 Paul,当我去附加我的 csv 文件时,我注意到了一些我应该首先发现的主要问题。一些我的 csv 文件如何添加一些字段...我不敢相信我没有抓住这个,但谢谢。
  • 没问题,试试row.join.blank? 应该也会做你想要的评估。

标签: ruby-on-rails-3 csv import sqlite rake-task


【解决方案1】:

有几种方法可以解决这个问题,但也许最简单的方法是添加:

unless row.join.blank?

你的代码会这样写:

csv.each_with_index do |row,index|
  unless row.join.blank?
    row = row.to_hash.with_indifferent_access
    MatList.create!(row.to_hash.symbolize_keys)
    matlist = MatList.last

    if @report_incident_hash.key?(matlist.report_nr)
      matlist.incident_id = "#{@report_incident_hash[matlist.report_nr]}"
    end

    #matlist.timesheet_id = @timesheet_id_array[index]
    matlist.save
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多