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
|
# File 'lib/has_bootstrap/model.rb', line 13
def has_bootstrap(*records)
primary_key = self.primary_key.to_sym
records.flatten!
ids = records.map { |record| record[primary_key] }.compact
delete_all(ids.any? ? ["#{primary_key} NOT IN (?)", ids] : nil)
existing = all.inject({}) do |existing, record|
existing[record.send(primary_key)] = record
existing
end
records.map! do |attributes|
attributes.symbolize_keys!
defaults = attributes.delete(:defaults)
record = if record = existing[attributes[primary_key]]
if defaults
available_defaults = defaults.delete_if do |attribute, value|
record.send("#{attribute}?")
end
attributes.merge! available_defaults
end
record.attributes = attributes
record
else
attributes.merge!(defaults) if defaults
new(attributes)
end
record.send(
"#{primary_key}=",
attributes[primary_key]
)
record.save!
record
end
records
end
|