Search code examples
ruby-on-rails-4rails-migrationsrake-task

How to run a big loop in a Rails rake task?


I have a loop like the following a in Ruby on Rails rake task.

Account.all.each do |a|

The problem is that there are 10 million records and memory goes up uncontrollably. How could I segment that to run a big loop?


Solution

  • You can use find_each that loads the record in batches.

    Another approach is to just load the IDs and then fetch each record once.

    I don't know what you are doing that requires loading your entire account table, but if it's a one-time task you have other possible alternatives such as using background jobs. If it's a recurring task or the result of a view, you may need to follow different approaches such as pagination.