Skip to content

Instantly share code, notes, and snippets.

@cbartlett
Created September 2, 2018 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbartlett/b6417f1251e6217e3a4e73de29b37d9a to your computer and use it in GitHub Desktop.
Save cbartlett/b6417f1251e6217e3a4e73de29b37d9a to your computer and use it in GitHub Desktop.
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