Last active
August 29, 2015 14:17
-
-
Save luxxi/59bbd57124b35ebe744b to your computer and use it in GitHub Desktop.
update_or_create
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
#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