Last active
October 14, 2020 01:36
-
-
Save aalavandhan/549fa9d7213485cad392 to your computer and use it in GitHub Desktop.
Rails Upsert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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