Module: ActiveRecordPatchFirstOrCreate

Defined in:
lib/active_record_patch_first_or_create.rb,
lib/active_record_patch_first_or_create/version.rb

Constant Summary collapse

VERSION =
"0.0.2"

Class Method Summary collapse

Class Method Details

.first_or_create(relation, attributes) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/active_record_patch_first_or_create.rb', line 4

def self.first_or_create relation, attributes
  attributes = attributes.merge(relation.where_values_hash)
  attributes = attributes.merge(rails_timestamps) if relation.klass.record_timestamps?

  sql = "INSERT INTO #{relation.table_name} (#{attributes.keys.join(",")})
         SELECT #{(['?'] * attributes.values.count).join(', ')}
         WHERE NOT EXISTS (#{relation.select('1').to_sql})"

  relation.klass.find_by_sql([sql] + attributes.values)

  relation.first
end

.rails_timestampsObject



17
18
19
20
# File 'lib/active_record_patch_first_or_create.rb', line 17

def self.rails_timestamps
  time = Time.now
  { created_at: time, updated_at: time }
end