Iterating through every record in a database - Ruby on Rails / ActiveRecord Iterating through every record in a database - Ruby on Rails / ActiveRecord ruby-on-rails ruby-on-rails

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 is not performant with large datasetsend

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.


Also a possible one-liner for same purpose:

User.all.map { |u| u.number = ""; puts u.number }