module RescueUniqueConstraint::ClassMethods

methods mixed into ActiveRecord class

Public Instance Methods

index_rescue_handler() click to toggle source
# 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:) click to toggle source
# File lib/rescue_unique_constraint.rb, line 23
def rescue_unique_constraint(index:, field:)
  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|
          errors.add(matching_index.field, :taken)
        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)
end