Skip to content

Instantly share code, notes, and snippets.

@hogihung
Last active March 31, 2016 20:29
Show Gist options
  • Save hogihung/677daec986e0e4c332a5 to your computer and use it in GitHub Desktop.
Save hogihung/677daec986e0e4c332a5 to your computer and use it in GitHub Desktop.
A rake Task for importing data via CSV files
require 'csv'
baytechs_file = "/path/to/file/baytechs.CSV"
devices_file = "/path/to/file/devices.CSV"
namespace :oob_import do
task :baytechs => :environment do
Baytech.delete_all
CSV.foreach(baytechs_file, headers: true) do |row|
p row
Baytech.create!(row.to_hash)
end
end
task :devices => :environment do
Device.delete_all
CSV.foreach(devices_file, headers: true) do |row|
baytech = Baytech.find_by_name("#{row[0]}")
baytech.devices.create!(name: "#{row[1]}", module: "#{row[2]}", pri_port: "#{row[3]}", active: "#{row[5]}", updated_by: "#{row[6]}", notes: "#{row[4]}")
p "BaytechID: #{baytech.id}, name: #{row[1]}, module: #{row[2]}, pri_port: #{row[3]}, active: #{row[5]}, updated_by: #{row[6]}, notes: #{row[4]}"
end
end
task :all => [:baytechs, :devices] do
puts "Refreshed Baytech and Device Models"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment