activerecord - Rails 4: find all records -
now activerecord::relation#all deprecated in rails 4, how supposed iterate records?
used like:
foo.all.each |foo| # whatever end
i can approximate so, feels dirty:
foo.where(true).each |foo| # whatever end
is there better way?
according rails guide on active record query interface, correct way iterate through records using find_each
.
using foo.all.each
load entire table memory, instantiating rows; iterate through instances. find_each
in batches, more efficient in terms of memory usage.
from guide:
the
find_each
method retrieves batch of records , yields each record block individually model. in following example,find_each
retrieve 1000 records (the current default bothfind_each
,find_in_batches
) , yield each record individually block model. process repeated until of records have been processed:
user.find_each |user| newsletter.weekly_deliver(user) end
references:
Comments
Post a Comment