Reputation: 19257
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
Reputation: 222388
Use update_all with the optional second parameter for the condition:
Model.update_all({ hidden: true }, { phonenum: some_phone_number})
Upvotes: 88
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
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