118

I have a class called CachedObject that stores generic serialized objects indexed by a key. I want this class to implement a create_or_update method. If an object is found it will update it, otherwise it will create a new one.

Is there a way to do this in Rails or do I have to write my own method?

8 Answers 8

223

Rails 6

Rails 6 added an upsert and upsert_all methods that deliver this functionality.

Model.upsert(column_name: value)

[upsert] It does not instantiate any models nor does it trigger Active Record callbacks or validations.

Rails 5, 4, and 3

Not if you are looking for an "upsert" (where the database executes an update or an insert statement in the same operation) type of statement. Out of the box, Rails and ActiveRecord have no such feature. You can use the upsert gem, however.

Otherwise, you can use: find_or_initialize_by or find_or_create_by, which offer similar functionality, albeit at the cost of an additional database hit, which, in most cases, is hardly an issue at all. So unless you have serious performance concerns, I would not use the gem.

For example, if no user is found with the name "Roger", a new user instance is instantiated with its name set to "Roger".

user = User.where(name: "Roger").first_or_initialize
user.email = "[email protected]"
user.save

Alternatively, you can use find_or_initialize_by.

user = User.find_or_initialize_by(name: "Roger")

In Rails 3.

user = User.find_or_initialize_by_name("Roger")
user.email = "[email protected]"
user.save

You can use a block, but the block only runs if the record is new.

User.where(name: "Roger").first_or_initialize do |user|
  # this won't run if a user with name "Roger" is found
  user.save 
end

User.find_or_initialize_by(name: "Roger") do |user|
  # this also won't run if a user with name "Roger" is found
  user.save
end

If you want to use a block regardless of the record's persistence, use tap on the result:

User.where(name: "Roger").first_or_initialize.tap do |user|
  user.email = "[email protected]"
  user.save
end
7
  • 1
    The source code that the document points to shows that this doesn't work the way you imply it does - the block is passed to a new method only if the corresponding record doesn't exist. There appears to be no "upsert" magic in Rails - you have to separate it into two Ruby statements, one for the object selection and one for the attribute update.
    – sameers
    Sep 23, 2014 at 5:08
  • @sameers I'm not sure I understand what you mean. What do you think I am implying?
    – Mohamad
    Sep 23, 2014 at 13:08
  • 1
    Oh... I see what you meant now - that both forms, find_or_initialize_by and find_or_create_by accept a block. I thought you meant that whether the record exists or not, a block will be passed down with the record object as an argument, in order to do the update.
    – sameers
    Sep 23, 2014 at 20:48
  • 3
    It is slightly misleading, not necessarily the answer, but the API. One would expect the block to be passed regardless, and thus could be create/updated accordingly. Instead, we have to break it out into separate statements. Boo. <3 Rails though :)
    – Volte
    Aug 26, 2015 at 16:44
34

In Rails 4 you can add to a specific model:

def self.update_or_create(attributes)
  assign_or_new(attributes).save
end

def self.assign_or_new(attributes)
  obj = first || new
  obj.assign_attributes(attributes)
  obj
end

and use it like

User.where(email: "[email protected]").update_or_create(name: "Mr A Bbb")

Or if you'd prefer to add these methods to all models put in an initializer:

module ActiveRecordExtras
  module Relation
    extend ActiveSupport::Concern

    module ClassMethods
      def update_or_create(attributes)
        assign_or_new(attributes).save
      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, ActiveRecordExtras::Relation
4
  • 1
    Won't assign_or_new return the first row in the table if it exists and then that row will get updated? It seems to be doing that for me. Apr 27, 2015 at 17:13
  • User.where(email: "[email protected]").first will return nil if not found. Make sure you have a where scope Apr 27, 2015 at 19:06
  • Just a note to say that updated_at won't be touched because assign_attributes is used
    – lshepstone
    Jan 28, 2018 at 19:00
  • It won't is you're using assing_or_new but will if you use update_or_create because of the save Jan 29, 2018 at 22:43
14

The magic you have been looking for has been added in Rails 6 Now you can upsert (update or insert). For single record use:

Model.upsert(column_name: value)

For multiple records use upsert_all :

Model.upsert_all(column_name: value, unique_by: :column_name)

Note:

  • Both methods do not trigger Active Record callbacks or validations
  • unique_by => PostgreSQL and SQLite only
1
  • 1
    Anyone using this in production? Not working as expected for me using 6.0.33 Rails. If I have a record [#<Model id: 1, other_model_fk: 33, some_property: 'foo'>] and then we call Model.upsert(other_model_fk: 33, some_property: 'bar') then a new row is added. (the FK column is indexed by the way). The behaviour we expect "If an object is found it will update it, otherwise it will create a new one." does not seem to be working. It's creating a new object. What am I missing here?
    – B. Bulpett
    Dec 3, 2020 at 13:31
13

Add this to your model:

def self.update_or_create_by(args, attributes)
  obj = self.find_or_create_by(args)
  obj.update(attributes)
  return obj
end

With that, you can:

User.update_or_create_by({name: 'Joe'}, attributes)
2
  • The second part I won't work. Can't update a single record from the class level without the ID of the record to update.
    – Aeramor
    Aug 29, 2016 at 23:52
  • 2
    obj = self.find_or_create_by(args); obj.update(attributes) ; return obj ;will work. Aug 11, 2017 at 10:28
3

By chaining find_or_initialize_by and update, this can be achieved in a simple way which avoids the (in my experience, often) unwanted caveats of upsert, and also minimises database calls.

For example:

Class.find_or_initialize_by(
  key: "foo",
  ...
).update(
  new_attribute: "bar",
  ...
)

will return you newly created or updated object.

It is worth noting that if your find_or_initialize_by attributes match multiple Class instances, only the 'first' one will be selected and updated.

1
  • Modelfind_or_initialize.tap is still better than this. The update here will make 2 db calls. First it will save the record with key: foo and then update it with new attributes. the tap will only do one db call. Jan 8 at 4:41
1

Old question but throwing my solution into the ring for completeness. I needed this when I needed a specific find but a different create if it doesn't exist.

def self.find_by_or_create_with(args, attributes) # READ CAREFULLY! args for finding, attributes for creating!
        obj = self.find_or_initialize_by(args)
        return obj if obj.persisted?
        return obj if obj.update_attributes(attributes) 
end
0

You can do it in one statement like this:

CachedObject.where(key: "the given key").first_or_create! do |cached|
   cached.attribute1 = 'attribute value'
   cached.attribute2 = 'attribute value'
end
1
  • 9
    This won't work, since it will only return the original record if one is found. The OP asks for a solution that always changes the value, even if a record is found.
    – JeanMertz
    Sep 1, 2014 at 11:55
0

The sequel gem adds an update_or_create method which seems to do what you're looking for.

2
  • 13
    The question is about Active Record.
    – freya
    Oct 25, 2015 at 16:01
  • Yes, the question is about AR but this gives an alternate way to solve the problem. It could be useful to people reading this question, who have a similar problem and may be open to using Sequel.
    – iconoclast
    Jan 25, 2022 at 18:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.