Class: ActiveRecord::Relation

Inherits:
Object
  • Object
show all
Defined in:
lib/atomic_first_or_create.rb

Instance Method Summary collapse

Instance Method Details

#atomic_first_or_create(**opts) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/atomic_first_or_create.rb', line 5

def atomic_first_or_create(**opts)
  # We do not want to retry forever to avoid getting stuck

  tries = 2
  begin
    first_or_create **opts
  rescue ActiveRecord::RecordNotUnique
    tries -= 1
    if tries.zero?
      raise
    end

    retry
  end
end