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
|
# File 'app/models/upload_reference.rb', line 9
def self.ensure_exist!(upload_ids: [], target: nil, target_type: nil, target_id: nil)
if !target && !(target_type && target_id)
raise "target OR target_type and target_id are required"
end
if target.present?
target_type = target.class
target_id = target.id
end
upload_ids = upload_ids.uniq.reject(&:blank?)
target_type = target_type.to_s
if upload_ids.empty?
UploadReference.where(target_type: target_type, target_id: target_id).delete_all
return
end
rows =
upload_ids.map do |upload_id|
{
upload_id: upload_id,
target_type: target_type,
target_id: target_id,
created_at: Time.zone.now,
updated_at: Time.zone.now,
}
end
UploadReference.transaction do |transaction|
UploadReference
.where(target_type: target_type, target_id: target_id)
.where.not(upload_id: upload_ids)
.delete_all
UploadReference.insert_all(rows)
end
end
|