Skip to content

Instantly share code, notes, and snippets.

@luxxi
Last active August 29, 2015 14:17
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 luxxi/59bbd57124b35ebe744b to your computer and use it in GitHub Desktop.
Save luxxi/59bbd57124b35ebe744b to your computer and use it in GitHub Desktop.
update_or_create
#Using in single model
def self.update_or_create(attributes)
obj = first || new
obj.assign_attributes(attributes)
obj
end
#User.where(email: "a@b.com").update_or_create(email: "d@e.com")
#Using in all models
#app/models/concerns/update_or_create.rb
module UpdateOrCreate
module Relation
extend ActiveSupport::Concern
module ClassMethods
def update_or_create(attributes)
assign_or_new(attributes)
end
def update_or_create!(attributes)
assign_or_new(attributes).save!
end
def assign_or_new(attributes)
obj = first || new
obj.assign_attributes(attributes)
obj
end
end
end
end
ActiveRecord::Base.send :include, UpdateOrCreate::Relation
#app/models/yourmodel.rb
include UpdateOrCreate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment