Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Why use find_ each?

find_each will take care of using batches if number of records are greater than batch_size . It also gives additional benefit of not hogging up application memory.

What is batch size in rails?

The size of each batch is set by the :batch_size option; the default is 1000. You can control the starting point for the batch processing by supplying the :start option. This is especially useful if you want multiple workers dealing with the same processing queue.


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.

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

It's basically like using ruby's lazy enumeration #to_enum#lazy with #each_slice and then #each (very convenient).