Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined method 'keys' when using upsert

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

like image 852
Samuel Da Costa Avatar asked Oct 22 '25 07:10

Samuel Da Costa


1 Answers

upsert_all expect an array of hashes, not ActiveRecord objects:

books = [] 

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

Book.upsert_all(books)
like image 99
BroiSatse Avatar answered Oct 24 '25 20:10

BroiSatse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!