Home Latest

latest / find_each silently ignores your ORDER BY

find_each batches by primary key, so it discards any custom ordering you put on the relation. In recent Rails it warns; older versions just drop it on the floor.

User.order(:last_seen_at).find_each do |user|
  # iterated by id ASC, not last_seen_at
end

If you actually need ordered iteration in batches, you have to do it yourself with cursoring on the ordered column, or just accept the memory hit of .order(:last_seen_at).each.

There’s also in_batches if you want the relation per batch rather than per record — handy for bulk updates:

User.where(active: false).in_batches.update_all(archived: true)