Skip to content

Instantly share code, notes, and snippets.

@csm123
Created March 28, 2021 20:48
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 csm123/8d28e01ae3841d44fde535e320b3f940 to your computer and use it in GitHub Desktop.
Save csm123/8d28e01ae3841d44fde535e320b3f940 to your computer and use it in GitHub Desktop.
create_or_update_unique method for Rails
# 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