Created
September 2, 2018 20:24
-
-
Save cbartlett/b6417f1251e6217e3a4e73de29b37d9a to your computer and use it in GitHub Desktop.
ActiveRecord upsert extension
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 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