Rails 4: find all records

后端 未结 4 1889
庸人自扰
庸人自扰 2021-01-31 14:02

Now that ActiveRecord::Relation#all is deprecated in Rails 4, how are you supposed to iterate all records?

Used to be like:

Foo.all.each do |foo|
  # w         


        
4条回答
  •  别那么骄傲
    2021-01-31 14:54

    According to the Rails Guide on Active Record Query Interface, the correct way to iterate through all records is by using 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.

    From the guide:

    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 both find_each and find_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
    

    References:

    • Active Record Query Interface
    • ActiveRecord::Batches

提交回复
热议问题