· 8 years ago · Mar 13, 2018, 04:46 AM
1#Script to load a CSV phonebook file into the Presence Phonebook
2require 'rubygems'
3require 'fastercsv'
4require 'active_record'
5require 'composite_primary_keys'
6
7# connect to the database (Oracle in this case)
8ActiveRecord::Base.establish_connection({
9 :adapter => "oracle",
10 :username => "uname",
11 :password => "passwd",
12 :database => "10.0.1.198/xe"
13})
14
15#Create our class for the PCO_PHONEBOOK table
16class PcoPhonebook < ActiveRecord::Base
17 set_table_name "PCO_PHONEBOOK"
18 set_primary_keys :serviceid, :phone
19end
20
21puts "Starting Phonebook loader..."
22puts " "
23
24#Create our counters to check status as we go
25cnt = 0
26increment_cnt = 0
27
28#Open the CSV file and loop through each record
29FasterCSV.foreach("NationsHealth_Phonebook.csv") do |row|
30
31 #Lookup the current row to see if it already exists in the database
32 phonebook_entry = PcoPhonebook.find(:first, :conditions => [ "serviceid = ? AND phone = ?", row[0], row[1] ])
33
34 #If the record exists, simply update the description field
35 if phonebook_entry != nil
36 phonebook_entry.description = row[3]
37 phonebook_entry.save
38 #If the record does not exist, then create a new entry
39 else
40 new_phonebook_entry = PcoPhonebook.new
41 new_phonebook_entry.serviceid = row[0]
42 new_phonebook_entry.phone = row[1]
43 new_phonebook_entry.phonetype = row[2]
44 new_phonebook_entry.description = row[3]
45 new_phonebook_entry.save
46 end
47
48 cnt += 1
49 increment_cnt += 1
50 if increment_cnt == 100
51 puts 'Records processed: ' + cnt.to_s
52 increment_cnt = 0
53 end
54end
55
56puts " "
57puts "Total records processed == " + cnt.to_s