2

rake タスクを使用して、17 個の csv ファイルをアプリにインポートしています。他のファイルは正常にインポートされ、余分な行は作成されませんが、何らかの理由で、このファイルがデータベースに約 60 の空の行を作成しています。インポートしようとしている情報は順調に進んでおり、適切なテーブルに適切に関連付けられています。したがって、アプリを使用すると、すべてが正常に機能しますが、テーブルが台無しになります。

たとえば、テーブルに 2 行をインポートすると、その 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
4

1 に答える 1

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
于 2012-10-30T17:39:47.963 に答える