If you are looking to update a lot of database records at once in Ruby on Rails then it's worth considering the different ways it can be done and which is the fastest and most efficient.
One way is to loop/iterate round a collection of objects and update each one in turn. Your code might look something like...
Foo.all.each do |foo|
foo.update_attributes(:bar => true)
end
However, it's worth noting that using a block in that way will instantiate each Foo object into memory and will also generate a mysql query per record. The advantage of this is that any Active Record callbacks will be triggered and each object will be validated.
Another, faster, way to do this generating just a single SQL UPDATE statement would be to use the update_all method like so...
Foo.update_all(:bar => true)
It does not instantiate the involved records and the single sql query makes this method faster and more efficient. However, it will not trigger any Active Record callbacks such as 'after_save' etc. so if you need these you'll have to go with the first method of updating each object in turn.
Note that the update_all method can accept conditions as second argument in the same format as the rails find method.
Foo.update_all({:bar => true}, ["id IN (?)", foo_ids])
Alternatively you can call update_all on named scopes.
About Paul
Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.
Follow Paul on Twitter
Email: paulsturgess [at] gmail.com
Comments...
Foo.update_all({:bar => true}, {:id => foo_ids})
works too.
codesnik at 08 Mar 10 at 18:36
Nice - thanks
Joel at 09 Apr 10 at 08:53
Small but useful information.
Nidhi Sarvaiya at 09 Feb 11 at 11:25
Got something to say?