Skip to content

Instantly share code, notes, and snippets.

@mguterl
Created February 12, 2013 21:14
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 mguterl/4773453 to your computer and use it in GitHub Desktop.
Save mguterl/4773453 to your computer and use it in GitHub Desktop.
module Upsertable
def upsert_added!
@upsert_added = true
end
def upsert_added?
@upsert_added
end
def upsert_updated!
@upsert_updated = true
end
def upsert_updated?
@upsert_updated
end
end
def upsert(key, attributes)
conditions = {}
key.each do |k|
value = attributes.fetch(k)
conditions[k] = value
end
record = records.first(:conditions => conditions)
if record
updated = true
else
record = records.build
end
record.extend Upsertable
if updated
record.upsert_updated!
else
record.upsert_added!
end
record.attributes = attributes
record.save!
record
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment