Ruby-on-rails 在 Rails 中,find_each 和 where 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30010091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:13:30  来源:igfitidea点击:

In Rails, what's the difference between find_each and where?

ruby-on-railsrubyruby-on-rails-3ruby-on-rails-4activerecord

提问by coderz

In Rails, both find_eachand whereare used for retrieving data from Database supported by ActiveRecord.

在 Rails 中,find_eachwhere都用于从 ActiveRecord 支持的数据库中检索数据。

You can pass your query condition to where, like:

您可以将查询条件传递给where,例如:

c = Category.where(:name => 'Ruby', :position => 1)

And you can pass batch size to find_each, like:

您可以将批量大小传递给find_each,例如:

Hedgehog.find_each(batch_size: 50).map{ |p| p.to_json }

But what's the difference between the following 2 code?

但是以下2个代码有什么区别?

# code 1
Person.where("age > 21").find_each(batch_size: 50) do |person|
  # processing
end

# code 2
Person.where("age > 21").each do |person|
  # processing
end

Does code 1 batch retrieve 50 tuples each time, and code 2 retrieve all tuples in one time? More details explaination is welcomed.

代码 1 批处理每次检索 50 个元组,代码 2 一次检索所有元组吗?欢迎更详细的解释。

My opinion is:

我的意见是:

  1. both whereand find_eachcan be used for batch retrieving, but user can define batch size when using find_each.
  2. find_eachdoes not support passing query condition.
  1. wherefind_each可用于批量检索,但是用户可使用时限定批量大小find_each
  2. find_each不支持传递查询条件。

Please correct me if my understanding is wrong.

如果我的理解有误,请指正。

回答by jphager2

An active record relation does not automatically load all records into memory.

活动记录关系不会自动将所有记录加载到内存中。

When you call #each, all records will be loaded into memory. When you call #find_each, records will be loaded into memory in batches of the given batch size.

当您调用 时#each,所有记录都将加载到内存中。当您调用 时#find_each,记录将按给定的批量大小分批加载到内存中。

So when your query returns a number of records that would be too much memory for the server's available resources, then using #find_eachwould be a great choice.

因此,当您的查询返回的记录数量对于服务器的可用资源来说内存过多时,使用#find_each将是一个不错的选择。

It's basically like using ruby's lazy enumeration #to_enum#lazywith #each_sliceand then #each(very convenient).

基本上就像使用 ruby​​ 的惰性枚举#to_enum#lazywith #each_slicethen #each(非常方便)。