本文介绍了Rails 4:查找所有记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在在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

有更好的方法吗?

推荐答案

根据,遍历所有记录的正确方法是使用。

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.

来自指南:



User.find_each do |user|
  NewsLetter.weekly_deliver(user)
end

参考文献:



  • Active Record Query Interface
  • ActiveRecord::Batches

这篇关于Rails 4:查找所有记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:37