Module: Dino::Upsert

Extended by:
ActiveSupport::Concern
Defined in:
lib/dino/upsert.rb

Overview

Provides a simple way to do an create or update of an ActiveRecord object.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.upsert(klass, data, options = {}, &block) ⇒ Object

klass: The ActiveRecord class we are upserting against. conditions: what should match the upsert options: what we are updating/inserting If provided, the block gets the object before it’s saved, in case

there's special init options necessary for it.

rubocop:disable MethodLength



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
# File 'lib/dino/upsert.rb', line 21

def self.upsert(klass, data, options = {}, &block)
  retry_count = 0
  data_copy = {}
  data ||= []
  data.each do |k, v|
    v = klass.column_for_attribute(k).type_cast_for_database(v) if v.is_a?(Hash)
    data_copy[k] = v
  end
  begin
    klass.transaction(requires_new: true) do
      object = klass.where(data_copy).first_or_initialize
      block.call(object) if block
      object.tap do |t|
        t.assign_attributes(options)
        t.save! if t.changed?
      end
    end
  rescue PG::UniqueViolation, ActiveRecord::RecordNotUnique
    # If there's a unique violation, retry this. But only a certain amount
    # of times or we'll get into an infinite loop if something's messed up.
    # (like an incorrect unique index or something)
    if retry_count < 10
      retry_count += 1
      retry
    else
      raise
    end
  end
end