views:

18

answers:

2

Hello all,

I need to update a single field across a large set of records. Normally, I would just run a quick SQL update statement from the console and be done with it, but this is a utility that end users need to be able to run in this app.

So, here's my code:

users = User.find(:all, :select => 'id, flag')
users.each do |u|
  u.flag = false
  u.save
end

I'm afraid this is just going to take a while as the number of users increases (current sitting at around 35k, adding 2-5k a week). Is there a faster way to do this?

Thanks!

A: 

You could use ActiveRecord's execute method to execute the update SQL. Something like this:

ActiveRecord::Base.connection.execute('UPDATE users SET flag=0')
John Topley
+2  A: 

If you really want to update all records, the easiest way is to use #update_all:

User.update_all(:flag => false)

This is the equivalent of:

UPDATE users SET flag = 'f'

(The exact SQL will be different depending on your adapter)

The #update_all method also accepts conditions:

User.update_all({:flag => false}, {:created_on => 3.weeks.ago .. 5.hours.ago})

Also, #update_all can be combined with named scopes:

class User < ActiveRecord::Base
  named_scope :inactive, lambda {{:conditions => {:last_login_at => 2.years.ago .. 2.weeks.ago}}
end

User.inactive.update_all(:flag => false)
François Beausoleil