blake.app

Rails for_each

Another Railsism I just learned about is the .find_each method which can be used to replace the .each method on large queries that will return more than 1,000 records.

Unlike my previous posts .find_each is not part of active support, and looks like it is part of active record.

Without .find_each you could run into a memory issue when just using .each:

Topic.where(archetype: "private_message").each do |pm|
  # do something
end

if there were thousands of records. But .find_each will by default use batches of 1000:

Topic.where(archetype: "private_message").find_each do |pm|
  # do something
end