How to use update all, when all records are different?

Markus picture Markus · Jan 7, 2012 · Viewed 12.8k times · Source

How can I use update_all, if I want to update a column of 300,000 records all with a variety of different values?

What I want to do is something like:

Model.update_all(:column => [2,33,94,32]).where(:id => [22974,22975,22976,22977]) 

But unfortunately this doesn't work, and it's even worse for 300,000 entries.

Answer

ouranos picture ouranos · Aug 13, 2013

From the ActiveRecord#update documentation:

people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
Person.update(people.keys, people.values)

So in your case:

updates = {22974 => {column: 2}, 22975 => {column: 33}, 22976 => {column: 94}, 22977 => {column: 32}}
Model.update(updates.keys, updates.values)

Edit: Just had a look at the source, and this is generating n SQL queries too... So probably not the best solution