Rails 4:查找所有记录 [英] Rails 4: find all records
问题描述
现在在Rails 4中已弃用ActiveRecord :: Relation#all了,您应该如何迭代所有记录?
Now that ActiveRecord::Relation#all is deprecated in Rails 4, how are you supposed to iterate all records?
以前是这样的:
Foo.all.each do |foo|
# whatever
end
我现在可以这样近似,但是感觉很脏:
I can approximate it now like so, but it feels dirty:
Foo.where(true).each do |foo|
# whatever
end
有更好的方法吗?
推荐答案
根据活动记录查询界面上的路轨指南,遍历所有记录的正确方法是使用 find_each
。
According to the Rails Guide on Active Record Query Interface, the correct way to iterate through all records is by using find_each
.
使用 Foo.all.each
会将 entire 表加载到内存中,实例化所有行;然后遍历实例。 find_each
分批执行此操作,这在内存使用方面更为有效。
Using Foo.all.each
will load the entire table into memory, instantiating all the rows; then iterate through the instances. find_each
does this in batches, which is more efficient in terms of memory usage.
来自指南:
find_each
方法检索一批记录,然后生成每条记录作为模型分别记录到块中。在下面的示例中,find_each
将检索1000条记录(find_each
和的当前默认设置) find_in_batches
),然后将每个记录作为模型分别生成到块中。重复此过程,直到处理完所有记录为止:
The
find_each
method retrieves a batch of records and then yields each record to the block individually as a model. In the following example,find_each
will retrieve 1000 records (the current default for bothfind_each
andfind_in_batches
) and then yield each record individually to the block as a model. This process is repeated until all of the records have been processed:
User.find_each do |user|
NewsLetter.weekly_deliver(user)
end
参考文献:
- Active Record Query Interface
- ActiveRecord::Batches
这篇关于Rails 4:查找所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!