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
|