Home > Net >  undefined method 'keys' when using upsert
undefined method 'keys' when using upsert

Time:10-29

I'd like to use the upsert_all method to insert (and update) record from a collection in a simple query, for example:

books = [] 

10.times do |i|
  books << Book.new(name: "book #{i}")
end

Book.upsert_all(books)

however, I get the following error:

.../activemodel-6.1.4.1/lib/active_model/attribute_methods.rb:469:in `method_missing': undefined method `keys' for #<Book id: nil, name: "book 0"> (NoMethodError)

And what I am looking for is to be able to make an insert all or upsert_all of an arbitrary collection as an books for example, if you could help me I would be grateful

CodePudding user response:

upsert_all expect an array of hashes, not ActiveRecord objects:

books = [] 

10.times do |i|
  books << { name: "book #{i}" }
end

Book.upsert_all(books)
  • Related