Class: Skadi::Demographic

Inherits:
ApplicationRecord show all
Defined in:
app/models/skadi/demographic.rb

Class Method Summary collapse

Class Method Details

.create_or_increment_all(demographics) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'app/models/skadi/demographic.rb', line 10

def self.create_or_increment_all(demographics)
  demographics_to_upsert = demographics.map do |demographic|
    {
      name: demographic[:name].strip[0, 255],
      value: demographic[:value].strip[0, 255],
      # SQL specifies NULL values are not equal, so we need to default the URI to an empty string
      # to ensure the unique index works correctly
      uri: demographic[:uri]&.strip&.[](0, 255) || "",
      recorded_on: Time.current,
      count: 1,
    }
  end

  Skadi::Demographic.upsert_all(
    demographics_to_upsert,
    unique_by: [ :uri, :name, :value, :recorded_on ],
    on_duplicate: Arel.sql("count = skadi_demographics.count + 1"),
    returning: false,
  )
end