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

Ruby on-RailsActiverecord

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Use update_all with the optional second parameter for the condition:

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

Solution 2 - Ruby on-Rails

The update_all does not allow conditions in rails 3. You can use combination of scope and update_all

Model.where(phonenum: some_phone_number).update_all(hidden: true)

Reference: http://m.onkey.org/active-record-query-interface

Solution 3 - Ruby on-Rails

If you want to trigger callbacks:

class ActiveRecord::Base
  def self.update_each(updates)
    find_each { |model| model.update(updates) }
  end

  def self.update_each!(updates)
    find_each { |model| model.update!(updates) }
  end
end

Then:

Model.where(phonenum: some_phone_number).update_each(hidden: true)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjpwView Question on Stackoverflow
Solution 1 - Ruby on-RailsDogbertView Answer on Stackoverflow
Solution 2 - Ruby on-RailsDeepak NView Answer on Stackoverflow
Solution 3 - Ruby on-RailsDorianView Answer on Stackoverflow