Ruby on Rails memory leak when looping through large number of records; find_each doesn’t help

I was able to figure this out myself. There are two places to change.

First, disable IdentityMap. In config/application.rb

config.active_record.identity_map = false

Second, use uncached to wrap up the loop

class MemoryTestController < ApplicationController
  def go
    ActiveRecord::Base.uncached do
      Person.find_each do |person|
        # whatever operation
      end
    end
  end
end

Now my memory use is under control. Hope this helps other people.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)