Rails 3 + activerecord, the best way to "mass update" a single field for all the records that meet a condition
Ruby on-RailsActiverecordRuby 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)
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)