Class: ActiveRecord::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/roqua/core_ext/activerecord/uniq_find_or_create.rb

Direct Known Subclasses

Roqua::Scheduling::CronJob

Class Method Summary collapse

Class Method Details

.uniq_find_or_create_by(attributes, &block) ⇒ Object

Use this method to find or create records that have uniqueness constraints enforced by the database. After calling the AR find_or_create_by method it queries the preexisting or created record by the attributes provided, thereby ensuring that a concurrently created record is returned when a AR RecordNotUnique error is raised. When no record can be found, because for instance validations fail on create, the created object containing the validation errors is returned instead.



10
11
12
13
14
# File 'lib/roqua/core_ext/activerecord/uniq_find_or_create.rb', line 10

def self.uniq_find_or_create_by(attributes, &block)
  find_or_create_by(attributes, &block)
rescue ActiveRecord::RecordNotUnique => exception
  find_by(attributes) || raise(exception)
end

.uniq_find_or_create_by!(attributes, &block) ⇒ Object

Use this method if you want an exception to be raised when creating a new record fails due to some validation error other than uniqueness.



18
19
20
21
22
23
24
# File 'lib/roqua/core_ext/activerecord/uniq_find_or_create.rb', line 18

def self.uniq_find_or_create_by!(attributes, &block)
  find_or_create_by!(attributes, &block)
rescue ActiveRecord::RecordNotUnique => exception
  find_by(attributes) || raise(exception)
rescue ActiveRecord::RecordInvalid => exception
  find_by(attributes) || raise(exception)
end