Skip to content

Instantly share code, notes, and snippets.

@cbartlett
Created Sep 2, 2018
Embed
What would you like to do?
ActiveRecord upsert extension
module Upsert
extend ActiveSupport::Concern
class_methods do
def upsert(key, attributes)
begin
create(attributes)
rescue ActiveRecord::RecordNotUnique => e
where(key => attributes[key]).
first.tap do |obj|
obj.update(attributes)
end
end
end
end
end
ActiveRecord::Base.send(:include, Upsert)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment