Rails 3 + activerecord, the best way to "mass update" a single field for all the records that meet a condition

jpw picture jpw · Feb 6, 2011 · Viewed 47k times · Source

In rails 3, using activerecord, is there a single-query way to set the :hidden field to TRUE for all records that meet a condition ... say, for example, :condition => [ "phonenum = ?", some_phone_number ]

If a single query cannot do it, what IS the optimal approach?

Answer

Dogbert picture Dogbert · Feb 6, 2011

Use update_all with the optional second parameter for the condition:

Model.update_all({ hidden: true }, { phonenum: some_phone_number})