Module: NxtSupport::SafelyFindOrCreateable::ClassMethods
- Defined in:
- lib/nxt_support/models/safely_find_or_createable.rb
Instance Method Summary collapse
- #safely_find_or_create_by(attributes, &block) ⇒ Object
- #safely_find_or_create_by!(attributes, &block) ⇒ Object
Instance Method Details
#safely_find_or_create_by(attributes, &block) ⇒ Object
6 7 8 9 10 |
# File 'lib/nxt_support/models/safely_find_or_createable.rb', line 6 def safely_find_or_create_by(attributes, &block) transaction(requires_new: true) { create(attributes, &block) } rescue ActiveRecord::RecordNotUnique find_by(attributes) end |
#safely_find_or_create_by!(attributes, &block) ⇒ Object
12 13 14 15 16 17 18 19 20 |
# File 'lib/nxt_support/models/safely_find_or_createable.rb', line 12 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 |