Skip to content

Instantly share code, notes, and snippets.

@aalavandhan
Last active October 14, 2020 01:36
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aalavandhan/549fa9d7213485cad392 to your computer and use it in GitHub Desktop.
Save aalavandhan/549fa9d7213485cad392 to your computer and use it in GitHub Desktop.
Rails Upsert
module ActiveRecordExtension
extend ActiveSupport::Concern
def self.upsert(attributes)
begin
create(attributes)
rescue ActiveRecord::RecordNotUnique, PG::UniqueViolation => e
find_by_primary_key(attributes['primary_key']).
update(attributes)
end
end
end
ActiveRecord::Base.send(:include, ActiveRecordExtension)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment