Module: RescueUniqueConstraint::ClassMethods

Defined in:
lib/rescue_unique_constraint.rb

Overview

methods mixed into ActiveRecord class

Instance Method Summary collapse

Instance Method Details

#index_rescue_handlerObject



19
20
21
# File 'lib/rescue_unique_constraint.rb', line 19

def index_rescue_handler
  @_index_rescue_handler ||= RescueUniqueConstraint::RescueHandler.new(self)
end

#rescue_unique_constraint(index:, field:, scope: nil) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rescue_unique_constraint.rb', line 23

def rescue_unique_constraint(index:, field:, scope: nil)
  unless method_defined?(:create_or_update_with_rescue)
    define_method(:create_or_update_with_rescue) do |*|
      begin
        create_or_update_without_rescue
      rescue ActiveRecord::RecordNotUnique => e
        self.class.index_rescue_handler.matching_indexes(e).each do |matching_index|
          if matching_index.scope
            errors.add(matching_index.field, :taken, unique_scope: matching_index.scope)
          else
            errors.add(matching_index.field, :taken)
          end
        end
        return false
      end
      true
    end

    alias_method :create_or_update_without_rescue, :create_or_update
    alias_method :create_or_update, :create_or_update_with_rescue
  end
  index_rescue_handler.add_index(index, field, scope)
end