If exists update else create. Either case return the record

ruby-on-rails, ruby-on-rails-3

Solution

The simplest thing is probably

object = Model.find_or_initialize_by_guid(guid)
object.update_attributes :value => value

Which always does 2 queries (a find and an insert/update)

If you know ahead of time that collisions are unlikely you could do

begin
  Model.create(:guid => guid, :value => value)
rescue ActiveRecord::RecordNotUnique
  # find and update existing record
end

This requires a unique index on the guid column. It requires 3 queries in the update case but only 1 query in the create case.

This all assumes we are talking SQL - other datastores, such as mongodb, have the concept of an upsert (update or insert) operation

Problem

Given `guid` and `value`. If a record exists with that `guid`, update its `value`. Otherwise, create a new record with that `guid` and `value`. Either case, return the record so that I can get its primary key `id`. How to do this with: - as less database queries as possible - as less code as possible

Original source