jpw
jpw

Reputation: 19257

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

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?

Upvotes: 75

Views: 47618

Answers (3)

Dogbert
Dogbert

Reputation: 222388

Use update_all with the optional second parameter for the condition:

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

Upvotes: 88

Deepak N
Deepak N

Reputation: 2571

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

Upvotes: 87

Dorian
Dorian

Reputation: 24009

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)

Upvotes: 5

Related Questions