Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update all when you need callbacks fired?

Let's say I've got 15 user ids in an array called user_ids.

If I want to, say, change all of their names to "Bob" I could do:

users = User.find(user_ids) users.update_all( :name => 'Bob' ) 

This doesn't trigger callbacks, though. If I need to trigger callbacks on these records saving, to my knowledge the only way is to use:

users = User.find(user_ids) users.each do |u|   u.name = 'Bob'   u.save end 

This potentially means a very long running task in a controller action, however.

So, my question is, is there any other better / higher performance / railsier way to trigger a batch update to a set of records that does trigger the callbacks on the records?

like image 980
Andrew Avatar asked Aug 03 '11 19:08

Andrew


1 Answers

Instead of using each/find_each, try using update method instead:

models.update(column: value) 

Which is just a wrapper for the following:

models.each{|x| x.update(column: value)} 
like image 184
untitled Avatar answered Sep 20 '22 12:09

untitled