Sha256: e489f710d35448492f58317a7ab97bf9fd1fad830747beaf14d4e8bddcf86ca2
Contents?: true
Size: 809 Bytes
Versions: 20
Compression:
Stored size: 809 Bytes
Contents
module NxtSupport module SafelyFindOrCreateable extend ActiveSupport::Concern module ClassMethods def safely_find_or_create_by(attributes, &block) transaction(requires_new: true) { create(attributes, &block) } rescue ActiveRecord::RecordNotUnique find_by(attributes) end def safely_find_or_create_by!(attributes, &block) transaction(requires_new: true) { create!(attributes, &block) } rescue ActiveRecord::RecordNotUnique find_by!(attributes) rescue ActiveRecord::RecordInvalid => e all_errors_are_uniqueness_failures = e.record.errors.details.all? { |_key, errs| errs.all? { |err| err[:error] == :taken } } raise unless all_errors_are_uniqueness_failures find_by!(attributes) end end end end
Version data entries
20 entries across 20 versions & 1 rubygems