5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
# File 'app/models/user.rb', line 5
def sync_contacts(contact_hash = {})
result = {:new => {success:[], failed:[]}, modified: {success:[], failed:[]}, deleted: {success:[], failed:[]}}
raise ArgumentError, "You need to provide contacts hash." if contact_hash.blank?
if !contact_hash[:new].blank?
contacts = contact_hash[:new]
contacts.each do |aContact|
phones = aContact[:phones]
emails = aContact[:emails]
aContact.delete :phones
aContact.delete :emails
newContact = Contact.new(contact_params(aContact))
if phones
phones.each do |aPhone|
newContact.phones.build(phone_params(aPhone))
end
end
if emails
emails.each do |anEmail|
newContact.emails.build(email_params(anEmail))
end
end
if newContact.save
self.contacts << newContact
else
result[:new][:failed] << newContact.record_id
end
end
end
if !contact_hash[:modified].blank?
modified_contacts = contact_hash[:modified]
modified_contacts.each do |con|
theContact = self.contacts.find_by_record_id(con[:record_id])
if ! theContact.blank?
if !theContact.update_attributes(contact_params(con))
result[:modified][:failed] << theContact.record_id
puts "Error Updating Contact."
else
end
end
end
end
if !contact_hash[:deleted].blank?
delete_contacts = contact_hash[:deleted]
delete_contacts.each do |con|
if self.contacts.find_by_record_id(con[:record_id].to_i).destroy
else
result[:deleted][:failed] << con[:record_id]
end
end
end
after_contact_sync
self.save
return result
end
|