Created
March 28, 2021 20:48
-
-
Save csm123/8d28e01ae3841d44fde535e320b3f940 to your computer and use it in GitHub Desktop.
create_or_update_unique method for Rails
This file contains 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
# A utility method for idempotent writes with ActiveRecord. | |
# Add a unique Postgres or MySQL index for the fields in `unique_attributes`. | |
# The method will look attempt to create a record. If it fails due to a | |
# unique index validation, it will update the existing record with the same | |
# unique attributes. | |
# Inpired by `create_or_find_by` in Rails 6, but serves a different use case. | |
# https://bigbinary.com/blog/rails-6-adds-create_or_find_by | |
class CreateOrUpdateUnique | |
def self.call(model, unique_attributes, non_unique_attributes, &block) | |
new_record = model.create!( | |
unique_attributes.merge(non_unique_attributes), | |
) | |
yield(new_record) if block_given? | |
new_record | |
rescue ActiveRecord::RecordNotUnique | |
existing_record = model.find_by!( | |
unique_attributes | |
) | |
existing_record.update!( | |
non_unique_attributes | |
) | |
existing_record | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment