0

I'm trying to take a populated array and empty its contents into specified table fields.

I have a rake file that's importing new rows via a CSV file that needs to extract the values from my already populated array and add them to the incident_id field.

For example:

@id_array = [97, 98, 99]

So, if I'm importing three new rows, the first row needs to get an incident_id of 97, the second row needs to get an incident_id of 98, and so on until the array is empty.

Here is the code for my rake file:

require 'csv'

namespace :import_timesheets_csv do

  task :create_timesheets => :environment do
    puts "Import Timesheets"

    csv_text = File.read('c:/rails/thumb/costrecovery_csv/lib/csv_import/timesheets.csv')
    csv = CSV.parse(csv_text, :headers => true)
    csv.each do |row|
      row = row.to_hash.with_indifferent_access
      Timesheet.create!(row.to_hash.symbolize_keys)
      timesheet = Timesheet.last
      timesheet.incident_id << @id_array
      timesheet.save
    end
  end
end
4

1 に答える 1

2
if csv.size == @id_array.size
  csv.each_with_index do |row,index|
    row = row.to_hash.with_indifferent_access
    Timesheet.create!(row.to_hash.symbolize_keys)
    timesheet = Timesheet.last
    timesheet.incident_id = @id_array[index]
    timesheet.save
  end
else
   #Handel error arrays are not equal in size
end
于 2012-09-27T17:45:37.830 に答える