activerecord - Updating a large record set in Rails -


i need update single field across large set of records. normally, run quick sql update statement console , done it, utility end users need able run in app.

so, here's code:

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

i'm afraid going take while number of users increases (current sitting @ around 35k, adding 2-5k week). there faster way this?

thanks!

if want update records, easiest way use #update_all:

user.update_all(:flag => false) 

this equivalent of:

update users set flag = 'f' 

(the exact sql different depending on adapter)

the #update_all method accepts conditions:

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

also, #update_all can combined 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) 

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -