I'm trying to read some values into an array in an .each do code block the simplest way possible but I'm having issues. I'm importing a csv file via a rake file I built, which will update a table with new rows, thus creating new id's. I'm trying to take each id that is created and save them into an array. And I'm wanting to be able to access the values stored in that array in another rake task.
The following code is for the rake file that will import the csv file and whose newly generated id's I wish to capture in an array. It currently does what it's supposed to do but you can only import one new row at a time.
Import_incidents_csv.rake
require 'csv'
namespace :import_incidents_csv do
task :create_incidents => :environment do
puts "Import Incidents"
csv_text = File.read('c:/rails/thumb/costrecovery_csv/lib/csv_import/incidents.csv')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
row = row.to_hash.with_indifferent_access
Incident.create!(row.to_hash.symbolize_keys)
end
@last_incident_id = Incident.last.id
end
end
This is another rake file that imports another csv file that I need to have the values stored in the array assigned to. And again, currently it works fine if you just import one new row, but if you import multiple rows then everything goes a little haywire.
Import_timesheets_csv.rake
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)
end
timesheet = Timesheet.last
timesheet.incident_id = @last_incident_id
timesheet.save
@last_timesheet_id = Timesheet.last.id
end
end
I read this resource for dealing with arrays http://www.tutorialspoint.com/ruby/ruby_arrays.htm and it seems very confusing. Here is my best guess of what the Import_incidents_csv.rake file might look like with reading values into an array. And I have the puts at the end so I can verify that the integers are properly getting stored in the array. Once I get everything working, I'll remove it.
require 'csv'
def inc_id
@inc_id = Incident.last.id
end
namespace :import_incidents_csv do
task :create_incidents => :environment do
puts "Import Incidents"
csv_text = File.read('c:/rails/thumb/costrecovery_csv/lib/csv_import/incidents.csv')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
row = row.to_hash.with_indifferent_access
Incident.create!(row.to_hash.symbolize_keys)
Incident.last.id = @inc_id
id_array = Array.new(@inc_id)
end
puts "#{id_array}"
end
end