The following Rails code results in 6 queries
people = { 1 => { "name" => "David" }, 2 => { "name" => "Jeremy" }, 3 => { "name" => "Tom" } }
Person.update(people.keys, people.values)
It will do TWO queries per updated row. One select and one update.
Is there a way to do the same task in Rails 4 with only one query (or only two queries)?
There are some information here on how to do it in MySQL, but not Rails: Multiple Updates in MySQL
Thanks.
No, but not for the reason @Sam D gave.
It's because if you go through ActiveRecord
, it's because you want to run validations, callbacks, etc. on the objects being updated. These validations and callbacks are not defined for a collection of objects.
You might say, "I don't care if they run." And that's fine. That's why rails gives you the ability to mass update through SQL directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With