Iterating through every record in a database – Ruby on Rails / ActiveRecord

Here is the correct syntax to iterate over all User :

User.all.each do |user|
  #the code here is called once for each user
  # user is accessible by 'user' variable

  # WARNING: User.all performs poorly with large datasets
end

To improve performance and decrease load, use User.find_each (see doc) instead of User.all. Note that using find_each loses the ability to sort.

Leave a Comment

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